包
Package | 包
导入
import "fmt"
fmt
is the name of a package that includes a variety of functions related to formatting and output to the screen. Bundling code in this way serves 3 purposes:
- It reduces the chance of having overlapping names. This keeps our function names short and succinct
- It organizes code so that its easier to find code you want to reuse.
- It speeds up the compiler by only requiring recompilation of smaller chunks of a program. Although we use the package
fmt
, we don’t have to recompile it every time we change our program.
未使用或副作用的导入
若导入某个包或声明某个变量而不使用它就会产生错误。未使用的包会让程序膨胀并拖慢编译速度,而已初始化但未使用的变量不仅会浪费计算能力,还有可能暗藏着更大的
我们可以将未使用的变量
package main
import (
"fmt"
"io"
"log"
"os"
)
var _ = fmt.Printf // For debugging; delete when done. // 用于调试,结束时删除。
var _ io.Reader // For debugging; delete when done. // 用于调试,结束时删除。
func main() {
fd, err := os.Open("test.go")
if err != nil {
log.Fatal(err)
}
// TODO: use fd.
_ = fd
}
空白赋值会将代码标识为工作正在进行中。但有时导入某个包只是为了其副作用,而没有任何明确的使用。例如,在
import _ "net/http/pprof"
init 函数
每个源文件都可以通过定义自己的无参数
尽管
// main.go
package main
import (
"fmt"
)
func init() {
fmt.Println("main")
}
func main() {
}
// b.go
package main
import (
"fmt"
)
func init() {
fmt.Println("b")
}
$ go build -o main main.go b.go
$ ./main
main
b
$ go build -o main b.go main.go
./main
b
main