Josh
Josh

Reputation: 587

How to use multiple .go files in the same application

Good Morning All,

I am new to Golang. I want to move some of my functions out into separate files so that I will not have like a 10,000 line .go file at the end. lol. I created two files both have the same package called main. Do I need to change package name to be app specific? Anyway how do I get these two files to talk?

Example:

MainFile.go:

package main

import (
    "fmt"
)

func main() {
    fmt.Println("Hello World!")

    Test()
}

NewFile.go:

package main

import (
    "fmt"
)

func Test() {
    fmt.Println("Hello World Again!")
}

The test method is in the second file but cannot be reached by the first. I am sure this is some rudimentary thing I am missing.

Thanks

Update: I tried specifying this on the command line: go build MainFile.go NewSourceFile.go. It comes back with no errors but never builds the binary. How do I get it to output the binary now?

Upvotes: 0

Views: 1794

Answers (1)

joshua
joshua

Reputation: 4198

If you run go run MainFile.go, Test() won't be found because its not in that file. You have to build the package then run the package:

Inside the folder where the 2 files are, run go build and you will get a binary in that folder. Then just run the binary: ./MyPackage

Upvotes: 2

Related Questions