为了账号安全,请及时绑定邮箱和手机立即绑定

如何获取接口的指针

如何获取接口的指针

Go
慕妹3146593 2022-04-26 10:51:13
很难解释,但是我怎样才能得到一个实现某个接口的东西的指针呢?考虑下面的代码:package mainimport (    "fmt"    "unsafe")type Interface interface {    Example()}type StructThatImplementsInterface struct {}func (i *StructThatImplementsInterface) Example() {}type StructThatHasInterface struct {    i Interface}func main() {    sameInterface := &StructThatImplementsInterface{}    struct1 := StructThatHasInterface{i: sameInterface}    struct2 := StructThatHasInterface{i: sameInterface}    TheProblemIsHere(&struct1)    TheProblemIsHere(&struct2)}func TheProblemIsHere(s *StructThatHasInterface) {    fmt.Printf("Pointer by Printf: %p \n", s.i)    fmt.Printf("Pointer by Usafe: %v \n", unsafe.Pointer(&s.i))}https://play.golang.org/p/HoC5_BBeswA结果将是:Pointer by Printf: 0x40c138 Pointer by Usafe: 0x40c140 Pointer by Printf: 0x40c138 Pointer by Usafe: 0x40c148 请注意,Printf获得相同的值(因为两者都StructThatHasInterface使用相同的sameInterface)。但是,unsafe.Pointer()返回不同的值。如果可能的话,我怎样才能得到与Printfwithout use相同的结果?fmtreflect
查看完整描述

1 回答

?
凤凰求蛊

TA贡献1825条经验 获得超4个赞

在当前版本的 Go 中,一个接口值是两个字长。具体值或指向具体值的指针存储在第二个字中。使用以下代码将第二个单词作为 a uintptr

  u := (*[2]uintptr)(unsafe.Pointer(&s.i))[1]

此代码不安全,不保证将来可以正常工作。

获取指针的支持方式是:

  u := reflect.ValueOf(s.i).Pointer()


查看完整回答
反对 回复 2022-04-26
  • 1 回答
  • 0 关注
  • 127 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号