gopackagego-modulespackage-name

In Go does the package name have to be identical to inner-most directory name?


ATTENTION this question is about Go language specs not best practice or recommendation.

I have read many articles of packages but I still don't quite understand the relationship of directory and package name. Here is my example.

My project structure is like the following screenshots. When I do go run ~/go/src/myproj/main.go the error says:

src\myproj\main.go:5:2: cannot find package "myproj/pa/pb" in any of: c:\go\src\myproj\pa\pb (from $GOROOT) C:\Users\terry\go\src\myproj\pa\pb (from $GOPATH)

enter image description here

enter image description here

However if I change package pb to package pa in p.go, and change the import from "myproj/pa/pb" to "myproj/pa", and change fmt.Print(pb.Greet) to fmt.Print(pa.Greet) in main.go, it will work. Does the inner most directory must match the package declaration name? My go version is 1.14.4


Solution

  • After some trials and errors I found out what happened. Package name has to be identical to inner-most directory name? No.

    In main.go just do the following it should work.

    package main
    
    import (
        "fmt"
        "myproj/pa"
    )
    
    func main() {
        fmt.Print(pb.Greet)
    }
    

    Also we can give it an alias such as the following also works.

    package main
    
    import (
        "fmt"
        pc "myproj/pa"
    )
    
    func main() {
        fmt.Print(pc.Greet)
    }
    

    So it means, package in go is a directory of files with package xxx declaration. The directory name matters during the import. The directory is part of the path for the import. But what is used in the imported file is the xxx in package xxx or the alias for that xxx.

    Of course, doing such kind of thing is not recommended, still the best practice is not to do this to confuse people.