← 中文资源

简体中文版本

debug.ReadBuildInfo 自报版本

debug.ReadBuildInfo 读出模块路径、Go 版本与 VCS 修订号,让 CLI 二进制自己打印版本信息。

阅读英文原文

实现说明

debug.ReadBuildInfo 自报版本可以归结为函数 main。 文件的主干是一个循环——for _, s := range info.Settings。

使用要点

  • 跑完文件,输出里会留下标记——build info unavailable、module:、go version:。

常见问题

运行「debug.ReadBuildInfo 自报版本」会打印什么?

整个文件跑完,输出行以 build info unavailable、module:、go version: 这类前缀开头。

核心语句

for _, s := range info.Settings {
	switch s.Key {
	case "-ldflags":
		fmt.Println("ldflags:", s.Value)
	case "vcs":
		vcs = s.Value
	case "vcs.revision":
		revision = s.Value
	}
}

代码示例

package main

import (
	"fmt"
	"runtime/debug"
)

func main() {
	info, ok := debug.ReadBuildInfo()
	if !ok {
		fmt.Println("build info unavailable")
		return
	}
	// the CLI stamps its own version from build info
	fmt.Println("module:", info.Main.Path)
	fmt.Println("go version:", info.GoVersion)
	if v := info.Main.Version; v != "" && v != "(devel)" {
		fmt.Println("version:", v)
	}
	var vcs, revision string
	for _, s := range info.Settings {
		switch s.Key {
		case "-ldflags":
			fmt.Println("ldflags:", s.Value)
		case "vcs":
			vcs = s.Value
		case "vcs.revision":
			revision = s.Value
		}
	}
	if vcs != "" && revision != "" {
		fmt.Printf("vcs: %s %s\n", vcs, revision)
	}
}