Reputation: 1487
I wish to learn how to logically split my code in a Go package into multiple files, and crucially, the syntax necessary to use that split/separate file in another file of the same package.
I have created a go project in this form
-test
-bin
-pkg
-src
-main
main.go
test.go
and attempted to run go build main
and go build main.go test.go
, but I have always got an error.
test.go contains only this code
package main
import "fmt"
func do(b string) {
fmt.Println(b)
}
I want to be able to call do("x")
in main.go.
Right now all that is in main.go is
package main
func main() {
test.do("x")
}
I do not know what to do to get this to work. Many answers seem to suggest moving test.go into a directory "test". I am hoping Go does not require me to make a directory for every piece of code I write, but maybe I would be "fighting the system". Many answers have pointed me to a website telling me to make the above directory structure, and to use go install
to compile my binaries, but that does not work.
I just want to know how to use functions in package/x.go inside package/y.go, even if they are in the same package. There has to be a way to do this, otherwise I will have either a bunch of unnecessary packages or hard to understand monolithic files.
I know there are many similar questions, but in my searching I haven't been able to find an actual example of the code in two files in the same package that reference each other.
Upvotes: 0
Views: 181
Reputation: 48310
test.go
has to be in the same package if is in the same directory. the package is thus main
for both of the files and being in the same package you can just call do("x")
.
Additionally you can build the entire package like this without specifying the single files.
export GOPATH="<path to>/test"
go build main
Upvotes: 4