I have a main.go file that I worked on and now I'm trying to organize since it became a little lengthy. I want to create a new file, put some functions in it and then include it in main.go and use those functions. That new file will be in the same directory as main.go. Anybody have any idea how to do this?
A package can have many files but only one file with main function, since that file will be the entry point of the execution. If a package does not contain a file with main package declaration, then Go creates a package archive ( . a ) file inside pkg directory. Since, app is not an executable package, it created app.
As long as the go files are in the same package, you do not need to import anything.
Example:
project/main.go:
package main
import "fmt"
func main() {
fmt.Println(sayHello())
}
project/utils.go:
package main
func sayHello() (string) {
return "hello!"
}
To run: go run main.go utils.go
or go run *.go
You don't have to do any including (importing). Just use the same package name in both files.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With