I have a simple question on the build process in Go.
I have a very simple app, the simplest possible, which is structured like this
- myapp
- main
- main.go
- go.mod
with main.go being
package main
import "fmt"
func main() {
fmt.Println("Hello !")
}
From within the folder myapp I run the command go build -o bin/main main/main.go and everything works.
No I decide to create a new function doStuff() in the package main to be called by main() but I want to have it in a different file stuff.go. So the new structure of the app is
- myapp
- main
- main.go
- stuff.go
- go.mod
with main.go being
package main
import "fmt"
func main() {
fmt.Println("Hello !")
doStuff()
}
and stuff.go being
package main
import "fmt"
func doStuff() {
fmt.Println("I am doing stuff")
}
If I try now to run the same build command go build -o bin/main main/main.go I get an error main/main.go:4:2: undefined: doStuff.
But if I move into the main folder and run from there the command go build -o ../bin/main everything works.
Which is the reason of this behaviour? Shall I always run the go build command from the folder where main() is if i want to create an executable?
If package
mainis split into multiple files, you can do either of the following:or
Main packages are typically very small. All business logic tends to either be in
pkg/orinternal/.