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 微信小程序协议怎么写
  • ¥15 c语言怎么用printf(“\b \b”)与getch()实现黑框里写入与删除?
  • ¥20 怎么用dlib库的算法识别小麦病虫害
  • ¥15 华为ensp模拟器中S5700交换机在配置过程中老是反复重启
  • ¥15 java写代码遇到问题,求帮助
  • ¥15 uniapp uview http 如何实现统一的请求异常信息提示?
  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看