将切片转换为数组指针仅在 -lang=go1.17 之后的版本中支持。

huangapple go评论111阅读模式
英文:

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

问题

我尝试在Go中使用新的切片转换为数组的方法,但是我得到了一个非常令人困惑的错误信息:

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

这让我感到困惑,因为go version报告的是1.17.6版本。

为什么它会抱怨一个据说在使用的版本中引入的东西?

-lang=go1.17是一个我可以/必须传递的标志吗?如果我尝试使用它,似乎没有任何效果。

编辑:我现在意识到它无论如何都会引发恐慌,但这并不是问题的重点。

英文:

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.

答案1

得分: 1

-lang标志是Go编译器的一个选项。

它通常由编译源代码的go命令设置,例如go build,基于go.mod中的go <version>指令。您可能在go.mod中有一个低于1.17的版本,这是引入从切片到数组指针的转换的版本。

您可以手动修复go.mod中的Go版本,或者通过运行go mod edit -go=1.17来修复。

实际上,即使您将go.mod保留为错误的版本(假设这是问题的原因),并直接使用适当的标志调用编译器,它也会进行编译:

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

附注:即使它编译成功,您的程序中的转换也会引发恐慌,因为数组长度(100)大于切片长度(40)。

英文:

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 &lt;version&gt; 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).

huangapple
  • 本文由 发表于 2022年2月24日 23:10:06
  • 转载请务必保留本文链接:https://go.coder-hub.com/71254115.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定