名前空間は、識別子の衝突を避ける分割です。Go の package はそれに加えて、export の境界であり、compile の単位です。同じ package の file は、file ごとに名前空間が分かれていません。

file はソースです。1つの directory にある、同じ package 名の file が 1 つの package になります。module は、その package をバージョン付きで配る単位です。
package は export の境界
同じ package の file は、unexported な宣言にもアクセスできます。別の package から使えるのは exported identifier だけです。
package block の宣言、field、method は、名前の先頭が Unicode の大文字(class Lu)なら export されます。
package user
type User struct {
Name string
id int
}
func New(name string) User { return User{Name: name, id: 1} }
func valid(u User) bool { return u.id != 0 }
func IsValid(u User) bool { return valid(u) }
| 識別子 | 同じ package | 他の package |
|---|---|---|
User | ○ | ○ |
User.Name | ○ | ○ |
User.id | ○ | × |
New | ○ | ○ |
valid | ○ | × |
IsValid | ○ | ○ |
main からは exported なものだけを呼びます。
package main
import (
"fmt"
"example.com/myapp/user"
)
func main() {
u := user.New("Alice")
fmt.Println(u.Name)
fmt.Println(user.IsValid(u))
// fmt.Println(u.id) // compile error
}
id の持ち方を変えても、New と IsValid の signature が同じなら、呼び出し側のソースは変わりません。
package は compile の単位
file の配置を次のようにします。
myapp/
├── go.mod
├── main.go
└── user/
├── user.go
└── validation.go
go build -x は、build が実行する command を表示します。
go build -x -o app .
初回の出力では、package ごとに compile が走り、その package の file がまとめて渡されます。
.../compile ... -p example.com/myapp/user ... ./user/user.go ./user/validation.go
.../compile ... -p main ... ./main.go
.../link ...
compile はコンパイラ、link は linker です。linker が executable を作ります。

compile user は user.go と validation.go をまとめて compile し、user.a を出します。user.a には export data と object code が入ります。
compile main が読むのは user の source ではなく、user.a の export data です。型検査に使う宣言と型がそこにあります。user.New は、次の形で渡ります。
func New(name string) User
inline や generics に必要な情報も export data に入ります。main.a にも export data と object code が入ります。
link が受け取るのは object code です。user.a と main.a の object code から executable app を作ります。図は、これ以外の依存を省いています。
build cache
package 単位で compile すると、結果を package ごとに再利用できます。Go 1.10 以降の build cache が、その結果を保存します。
同じ command をもう一度実行します。
go build -x -o app .
source も build 条件も変わっていなければ、compile は再実行されません。保存先の directory は、go env GOCACHE を実行すると表示されます。
validation.go にコメントを足します。
func IsValid(u User) bool { return valid(u) } // comment only
compile の単位は package なので、user は user.go と validation.go を compile し直します。この変更では export data は変わりません。main は compile し直されません。
valid の本体を変えます。
func valid(u User) bool { return u.id > 0 }
IsValid の signature は同じです。valid は IsValid に inline されるので、export data は変わります。main の compile もやり直しになります。user を import していない package の cache はそのままです。