packagemainimport("flag""fmt""os")//需要赋值的变量
varversion=""//通过flag包设置-version参数
varprintVersionboolfuncinit(){flag.BoolVar(&printVersion,"version",false,"print program build version")flag.Parse()}funcmain(){ifprintVersion{println(version)os.Exit(0)}fmt.Printf("example for print version")}
构建命令:
1
go build -ldflags "-X main.version=v0.1" -o example
程序输出:
1
2
➜ ./example
version=v0.1
参数说明
1、-ldflags build命令中用于调用接链接器的参数
1
2
-ldflags '[pattern=]arg list'
arguments to pass on each go tool link invocation.
2、-X 链接器参数,主要用于设置变量
1
2
3
4
-X importpath.name=value
Set the value of the string variable in importpath named name to value.
Note that before Go 1.5 this option took two separate arguments.
Now it takes one argument split on the first = sign.
packagemainimport("flag""github.com/go-demo/version")//通过flag包设置-version参数
varprintVersionboolfuncinit(){flag.BoolVar(&printVersion,"version",false,"print program build version")flag.Parse()}funcmain(){ifprintVersion{version.PrintVersion()}}