dqly83915 2015-12-15 21:17
浏览 28
已采纳

如果编译器只是一个点发布版本太旧,有没有办法使Golang编译失败?

Specifically, for our next software release, I want to make sure to catch a bug fix that was released in go 1.5.2; is there a way to make the build fail if our build server tries to build my code using Go 1.5.1 or earlier?

I know about Build Constraints, and I can see how I can add a build constraint of "go1.5" to make sure the "1.5 or greater" compiler is used, but "go1.5.2" doesn't work (it appears that build tags go1.5.1 and go1.5.2 are not defined.)

On a related note, I also can't find a way to dump out the build tags that apply for a build, and yet this seems to be a pretty useful thing to do.

  • 写回答

1条回答 默认 最新

  • duanqiao1947 2015-12-15 23:42
    关注

    You can use the -ldflags to pass the configured min golang build and check at init() time if the runtime matches the specified version.

    package main
    
    import "runtime"
    
    // go run -ldflags "-X main.minGoVersion=go1.5.1" main.go
    
    // from http://stackoverflow.com/questions/18409373/how-to-compare-two-version-number-strings-in-golang
    func VersionOrdinal(version string) string {
        // ISO/IEC 14651:2011
        const maxByte = 1<<8 - 1
        vo := make([]byte, 0, len(version)+8)
        j := -1
        for i := 0; i < len(version); i++ {
            b := version[i]
            if '0' > b || b > '9' {
                vo = append(vo, b)
                j = -1
                continue
            }
            if j == -1 {
                vo = append(vo, 0x00)
                j = len(vo) - 1
            }
            if vo[j] == 1 && vo[j+1] == '0' {
                vo[j+1] = b
                continue
            }
            if vo[j]+1 > maxByte {
                panic("VersionOrdinal: invalid version")
            }
            vo = append(vo, b)
            vo[j]++
        }
        return string(vo)
    }
    
    var minGoVersion string
    
    func init() {
        if minGoVersion == "" {
            panic("please pass  -ldflags \"-X main.minGoVersion=<version string> flag\"")
        }
    
        current := VersionOrdinal(runtime.Version())
        desired := VersionOrdinal(minGoVersion)
        if current < desired {
            panic("unsupported golang runtime " + current + " < " + desired)
        }
    }
    
    func main() {
    
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 #MATLAB仿真#车辆换道路径规划
  • ¥15 java 操作 elasticsearch 8.1 实现 索引的重建
  • ¥15 数据可视化Python
  • ¥15 要给毕业设计添加扫码登录的功能!!有偿
  • ¥15 kafka 分区副本增加会导致消息丢失或者不可用吗?
  • ¥15 微信公众号自制会员卡没有收款渠道啊
  • ¥100 Jenkins自动化部署—悬赏100元
  • ¥15 关于#python#的问题:求帮写python代码
  • ¥20 MATLAB画图图形出现上下震荡的线条
  • ¥15 关于#windows#的问题:怎么用WIN 11系统的电脑 克隆WIN NT3.51-4.0系统的硬盘