我正在做一些有关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)
}
我该怎么做?
答案 0 :(得分:0)
使用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)
}