很難解釋,但是我怎樣才能得到一個實現某個接口的東西的指針呢?考慮下面的代碼: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()
- 1 回答
- 0 關注
- 116 瀏覽
添加回答
舉報
0/150
提交
取消