打包和工具链
包
- 所有Go语言的程序都会组成若干组文件,每组文件被称为一个包。包利于复用
- 包命名惯例 给包命名的惯例是使用包所在目录的名字
- main包
所有用 Go 语言编译的可执行程序都必须有一个名叫 main 的包 和main函数。main函数是程序入口,没有则程序无法执行 - 导入包
- 远程导入
如import “github.com/spf13/viper”,使用GOPATH设置在磁盘上搜错,可以使用go get获取 - 命名导入 别名
如果发现了重名的包 可以使用命名导入
import (
"fmt"
myfmt "mylib/fmt" 别名导入
)
函数init
每个包可以包含任意多个 init 函数,这些函数都会在程序执行开始的时候被调用。所有被 编译器发现的 init 函数都会安排在 main 函数之前执行。init 函数用在设置包、初始化变量 或者其他要在程序运行前优先完成的引导工作
GO工具
命令行直接输入go,可以看到
阿斯蒂芬@发送到-Air /$ go
Usage:
go <command> [arguments]
The commands are:
bug start a bug report
构建包
build compile packages and dependencies
删除编译生成的可执行文件
clean remove object files and cached files
先构建包含的程序,然后执行构建后的程序
run compile and run Go program
检测代码常用错误
vet report likely mistakes in packages
格式化代码
fmt gofmt (reformat) package sources
查看文档, godoc -http=:6060 可以本地浏览 127.0.0.1:6060
doc show documentation for package or symbol
env print Go environment information
fix update packages to use new APIs
generate generate Go files by processing source
get download and install packages and dependencies
install compile and install packages and dependencies
list list packages or modules
mod module maintenance
test test packages
tool run specified go tool
version print Go version
Use "go help <command>" for more information about a command.
Additional help topics:
buildmode build modes
c calling between Go and C
cache build and test caching
environment environment variables
filetype file types
go.mod the go.mod file
gopath GOPATH environment variable
gopath-get legacy GOPATH go get
goproxy module proxy protocol
importpath import path syntax
modules modules, module versions, and more
module-get module-aware go get
packages package lists and patterns
testflag testing flags
testfunc testing functions
Use "go help <topic>" for more information about that topic.
本文详细介绍Go语言中包的概念,包括包的命名惯例、main包的作用、如何导入包及使用命名导入解决包名冲突。此外,文章还深入探讨了init函数的应用场景,以及Go工具链的各种实用命令,如构建、清理、运行、检测、格式化等。
1816

被折叠的 条评论
为什么被折叠?



