2017年11月6日星期一

Package name VS. directory name in Golang

So conventionally a golang package should be named after the directory where its code resides. What if I break the convention?

Well, you'd be frowned upon, for starters. And your code would be less readable. But it's not totally forbidden.

From a technical standpoint:
A Go package has both a name and a path. The package name is specified in the package statement of its source files; client code uses it as the prefix for the package's exported names. Client code uses the package path when importing the package. By convention, the last element of the package path is the package name.

So say you have a package that resides in the directory samplepkg, but the package name is anotherpkg. You should import from samplepkg, and refer to its exported types/functions with anotherpkg.

package main

import (
        "fmt"
        "github.com/tonyyang132/hello-world/samplepkg"
)

func main() {
        fmt.Println(anotherpkg.Msg())
}