GO语言实战三 打包和工具链

本文详细介绍Go语言中包的概念,包括包的命名惯例、main包的作用、如何导入包及使用命名导入解决包名冲突。此外,文章还深入探讨了init函数的应用场景,以及Go工具链的各种实用命令,如构建、清理、运行、检测、格式化等。

打包和工具链

  1. 所有Go语言的程序都会组成若干组文件,每组文件被称为一个包。包利于复用
  2. 包命名惯例 给包命名的惯例是使用包所在目录的名字
  3. main包
    所有用 Go 语言编译的可执行程序都必须有一个名叫 main 的包 和main函数。main函数是程序入口,没有则程序无法执行
  4. 导入包
  • 远程导入
    如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.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值