Continuing our examination of scope…
Declarations and scope
…
- The scope of the package name of an imported package is the file block of the file containing the import declaration.
The only thing that goes in the file block are imported package names. This is why you must repeat an import statement for every file that uses a symbol from the imported package. So for example, given two files in the same package:
foo.go
:
package foo
import "fmt"
func foo() {
fmt.Println("foo!")
}
bar.go
:
package foo
func bar() {
fmt.Println("bar!") // Won't compile since "fmt" is not imported in this file
}
This also means you can import the same package in different files, but using different names:
baz.go
:
pacakge baz
import tmf "fmt"
func baz() {
tmf.Println("baz!") // This works, while "fmt" would not in this file,
// because the import name in this file is "tmf"
}
Quotes from [_The Go Programming Language Specification_](https://go.dev/ref/spec) Version of December 15, 2022