亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

如何獲取接口的指針

如何獲取接口的指針

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 關注
  • 116 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號