Importing Code from Adjacent File in Go
In Go, a program is defined by a single un- imported main
package. You can't have multiple main
packages in a program, so if you want to make a library, e.g. your foo
dir, you need to define a different package name.
Imports are handled in Go as follows:
1. They are taken relative to $GOPATH
.
2. You can't import a package relative to a specific file.
Example:
Consider the following code:
hello.go:
package main
import . "huru/foo"
func main() {
SayHi()
}
foo/side.go:
package foo
import "fmt"
func SayHi() {
fmt.Println("Hello from side.go");
}
In this example, the hello.go
program imports the huru/foo
package and calls the SayHi()
function, which is defined in the foo/side.go
file.
This code will work fine as long as the package names are different. In this case, main
and foo
are different package names.
Additional Points:
* You can't use main
as the package name of huru/foo/side.go
, because it's already used in the huru/hello.go
.
* It's better to use the folder name as the package name.