我正在做一些关于 unsafe.Pointer 的测试。假设TestFun是一个公共库函数,那么“Person”结构体不应该出现在这个函数中type Person struct { Name string}func main() { p := &Person{} p.Name = "TestName" TestFun(p)}func TestFun(val interface{}) { // I want to convert interface{} to unsafe.Pointer var pointer unsafe.Pointer // This Line compile error //pointer = unsafe.Pointer(val) // This is ok, but "Person" appears. This function is a common function, "Person" should not appear // pointer = unsafe.Pointer(val.(*Person)) println(pointer)}我怎么能这样做呢?
1 回答
慕森卡
TA贡献1806条经验 获得超8个赞
而不是unsafe.Pointer(val)使用unsafe.Pointer(&val). 因为它接受指针。
package main
import (
"unsafe"
)
type Person struct {
Name string
}
func main() {
p := &Person{}
p.Name = "TestName"
TestFun(p)
}
func TestFun(val interface{}) {
// I want to convert interface{} to unsafe.Pointer
var pointer unsafe.Pointer
pointer = unsafe.Pointer(&val)
println(pointer)
u := (*interface{})(pointer)
p := (*u).(*Person)
println(p.Name)
}
- 1 回答
- 0 关注
- 126 浏览
添加回答
举报
0/150
提交
取消