英文:
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 <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).
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论