go - 如何获取接口(interface)的指针

标签 go unsafe-pointers

很难解释,但是我怎样才能得到一个实现某个接口(interface)的东西的指针呢?

考虑下面的代码:

package main

import (
    "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()返回不同的值。

如何获得与 Printf 相同的结果不用fmt , 和 reflect如果可能的话?

最佳答案

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

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

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

获取指针的支持方式是:
  u := reflect.ValueOf(s.i).Pointer()

关于go - 如何获取接口(interface)的指针,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59340441/

相关文章:

c# - 声明指向类定义结构的指针,其中类是通用的

go - 使用统一建模语言图编程 Go

go - 结构的私有(private)字段和方法

go - 在具有基础字段的任何结构数组上调用方法

ios - Swift 3 中的 UnsafePointer<UInt8> 初始值设定项

objective-c - 无法在 Swift 中分配 UnsafeMutablePointer ObjCBool​​ 类型的值

go - 相当于 Go 的 WTForms?

go - 为结构字段分配默认值

swift - 指向 Swift 中最后一个数组元素的不安全指针

swift - 将 C char 数组(不安全指针)转换为 String