正如在Spec中提到的,将片转换为数组指针会产生指向片的底层数组的指针.
s := make([]byte, 2, 4)
s0 := (*[0]byte)(s) // s0 != nil
但编译器给出错误:cannot convert s (variable of type []byte) to *[0]byte
正如在Spec中提到的,将片转换为数组指针会产生指向片的底层数组的指针.
s := make([]byte, 2, 4)
s0 := (*[0]byte)(s) // s0 != nil
但编译器给出错误:cannot convert s (variable of type []byte) to *[0]byte
这一转换是在Go 1.17年添加到语言中的.
对语言的更改
Go 1.17包括对该语言的三个小增强.
- Conversions from slice to array pointer:现在可以将类型
[]T
的表达式s
转换为数组指针类型*[N]T
.如果a
是这种转换的结果,则在范围内的对应索引引用相同的基础元素:&a[i] == &s[i] for 0 <= i < N
.如果len(s)
小于N
,则转换会引发panic .- [.]
这意味着您需要Go 1.17或更高版本才能使用此类转换.它在Go Playground上运行良好(目前playground 使用的是最新的GO 1.19).