猿问

interface{} 转换为 unsafe.Pointer 问题

我正在做一些关于 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)

}

我怎么能这样做呢?


慕村225694
浏览 128回答 1
1回答

慕森卡

而不是unsafe.Pointer(val)使用unsafe.Pointer(&val). 因为它接受指针。package mainimport (    "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)}
随时随地看视频慕课网APP

相关分类

Go
我要回答