仅从 -lang=go1.17 开始支持将切片转换为数组指针
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
应该是我can/must通过的标志吗?如果我尝试它似乎没有任何作用。
编辑:我现在意识到无论如何它都会恐慌,但这不是问题的重点。
-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
PS:即使编译通过,你程序中的转换也会出现panic,因为数组长度(100)大于切片长度(40)。
我试图在 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
应该是我can/must通过的标志吗?如果我尝试它似乎没有任何作用。
编辑:我现在意识到无论如何它都会恐慌,但这不是问题的重点。
-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
PS:即使编译通过,你程序中的转换也会出现panic,因为数组长度(100)大于切片长度(40)。