0

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.

blackgreen
  • 34,072
  • 23
  • 111
  • 129
Pete
  • 1,241
  • 2
  • 9
  • 21
  • 3
    The error could be caused by the Go version in `go.mod` being lower than 1.17. Also note that that conversion isn't valid anyway because the array length (100) is greater than the slice's (40) – blackgreen Feb 24 '22 at 15:15
  • It could also be this: https://github.com/golang/go/issues/44976 – Paul Hankin Feb 24 '22 at 15:16
  • 1
    Run `go mod edit -go=1.17`, see [How to upgrade the go version in a go mod](https://stackoverflow.com/questions/60675415/how-to-upgrade-the-go-version-in-a-go-mod/60675491#60675491) – icza Feb 24 '22 at 15:18
  • @blackgreen it was go.mod. If you want to put that in an answer I'll give it the tick. – Pete Feb 25 '22 at 08:42

1 Answers1

1

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).

blackgreen
  • 34,072
  • 23
  • 111
  • 129