gpt4 book ai didi

go - interface{}转unsafe.Pointer问题

转载 作者:数据小太阳 更新时间:2023-10-29 03:36:14 25 4
gpt4 key购买 nike

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

我该怎么做?

最佳答案

使用 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)
}

关于go - interface{}转unsafe.Pointer问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56554574/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com