我很好奇爲什麼只是在var上打印內存地址直接工作,但試圖通過接口執行相同的操作不會打印出內存地址?Golang:打印內存地址的接口函數
package main
import "fmt"
type address struct {
a int
}
type this interface {
memory()
}
func (ad address) memory() {
fmt.Println("a - ", ad)
fmt.Println("a's memory address --> ", &ad)
}
func main() {
ad := 43
fmt.Println("a - ", ad)
fmt.Println("a's memory address --> ", &ad)
//code init in here
thisAddress := address{
a: 42,
}
// not sure why this doesnt return memory address as well?
var i this
i = thisAddress
i.memory()
}
https://play.golang.org/p/Ko8sEVfehv
只是想修正錯誤後添加此,它現在預期的功能。 測試移位存儲器指針
package main
import "fmt"
type address struct {
a int
}
type this interface {
memory() *int
}
func (ad address) memory() *int {
/*reflect.ValueOf(&ad).Pointer() research laws of reflection */
var b = &ad.a
return b
}
func main() {
thisAddress := address{
a: 42,
}
thatAddress := address{
a: 43,
}
var i this
i = thisAddress
a := i.memory()
fmt.Println("I am retruned", a)
fmt.Println("I am retruned", *a)
i = thatAddress
c := i.memory()
fmt.Println("I am retruned", c)
fmt.Println("I am retruned", *c)
}
https://play.golang.org/p/BnB14-yX8B
在這種情況下,您應該使用'reflect'包。 'reflect.ValueOf(&ad).Pointer()'將返回&ad(這是一個指針值)作爲'uintptr'。 –
謝謝,剛擡起頭反映我現在正在閱讀反射法則。 –