conversion of slices to array pointers only supported as of -lang=go1.17

Issue

I attempted to use the new conversion of slice to array in Go, but I get a very confusing error message:

func TestName(t *testing.T) {
    a := [100]int{}

    b := a[10:50]
    _ = b
    fmt.Println(runtime.Version())

    c := (*[100]int)(b)
}
sh-3.2$ go test
# 
./....go: cannot convert b (type []int) to type *[100]int:
        conversion of slices to array pointers only supported as of -lang=go1.17

Which is confusing me because go version reports 1.17.6.

Why is it complaining about something that is supposedly introduced in the version it is using?

Is -lang=go1.17 supposed to be a flag I can/must pass? it doesn’t seem to do anything if I try it.

Edit: I now realise it would have panicked anyway, but that’s not really the point of the question.

Solution

The -lang flag is an option of the Go compiler.

It is usually set by go commands that compile sources, e.g. go build, based on the go <version> directive in go.mod. You likely have a version in go.mod lower than 1.17, which is the version that introduces conversion from slice to array pointers.

You can fix the Go version in go.mod by hand or by running go mod edit -go=1.17.

As a matter of fact, if you leave go.mod with the wrong version (assuming that was the culprit) and invoke the compiler directly with the appropriate flag, it will compile:

go tool compile -lang go1.17 ./**/*.go

PS: even if it compiles, the conversion in your program will panic because the array length (100) is greater than the slice length (40).

Answered By – blackgreen

Answer Checked By – Katrina (GoLangFix Volunteer)

Leave a Reply

Your email address will not be published.