go

Can I require a minimum Go version when compiling an app?


I'd like to make sure people aren't using Go 1.12 or older when compiling my application; mainly because this:

return fmt.Errorf("foo: %w", err)

Will compile fine in Go 1.12, but won't actually behave as expected as it requires runtime changes in Go 1.13 or newer to pick up on that %w.

And even there are changes which introduce a compile error, such as binary literals or _ in numeric literals, a nicer "you need Go 1.13 or newer"-message would be better and less confusing, as not everyone may be familiar with Go and know what to do with a syntax error (it seems some people still use rather old Go versions).

I added go 1.13 to my go.mod file, but I can still compile it fine with older versions (and adding go 1.16 and compiling with Go 1.15 also works).

Is there any way to require a minimum Go version when compiling an app to prevent runtime errors and display a friendly error message?


Solution

  • The easiest way I could figure out is adding a new file with +build !go1.13; since Go version build tags are added for all newer versions (Go 1.14 has go1.14, go1.13, go1.12, etc.) it will compile only for versions older than Go 1.13, and will be ignored for any newer versions:

    // +build !go1.13
    
    package main
    
    func init() {
        "You need Go 1.13 or newer to compile this program"
    }
    

    This introduces a deliberate compile error, which results in a reasonably nice error message:

    $ go install ./cmd/app
    # zgo.at/app/cmd/app
    cmd/app/old.go:8:2: "You need Go 1.13 or newer to compile this program" evaluated but not used