I m quite new to Go coming from C++ background and have stumbled upon some weird issue. Here s the code:
package main
import (
"fmt"
"unsafe"
)
func main() {
arr := []string { "one", "two", "three" }
address := unsafe.Pointer(&arr)
addPtr := (*[]string)(unsafe.Pointer(*(*uintptr)(address)))
fmt.Println((*addPtr)[0])
}
此代码失败的原因如下:
运行时错误:growtslice:len超出范围
例如,如果我将演员阵容更改为:
addPtr := (*[0]string)(unsafe.Pointer(*(*uintptr)(address)))
上面的代码工作得很好。
I understand that this is a cast to an array pointer and array must have constant size, but how to cast it to pointer to a slice then?
更令人困惑的是,可以采用切片的地址并将其分配给指针,如下所示:
func main() {
arr := []string { "one", "two", "three" }
var arrPtr *[]string = &arr
fmt.Println((*arrPtr)[0])
}
And this time everything will work despite the fact that the type of pointer is the same type that i was casting unsafe pointer to in the first example. Can someone help to understand what s exactly going on here?