See this experiment.
~/go/src$ tree -F
.
├── 1-foodir/
│ └── 2-foofile.go
└── demo.go
1 directory, 2 files
~/go/src$ cat demo.go
package main
import (
"fmt"
"1-foodir"
)
func main() {
fmt.Println(foopkg.FooFunc())
}
~/go/src$ cat 1-foodir/2-foofile.go
package foopkg
func FooFunc() string {
return "FooFunc"
}
~/go/src$ GOPATH=~/go go run demo.go
FooFunc
I thought that we always import a package name. But the above example
shows that we actually import a package directory name ("1-foodir"
)
but while invoking exported names within that package, we use the
package name declared in the Go files (foopkg.FooFunc
).
This is confusing for a beginner like me who comes from Java and Python world, where the directory name itself is the package name used to qualify modules/classes defined in the package.
Why is there a difference in the way we use import
statement and
refer to names defined in the package in Go? Can you explain the rules
behind these things about Go?
#PackageNames
under ` golang.org/doc/code.html` any longer. – Unrepair