【发布时间】:2016-09-28 06:37:35
【问题描述】:
我很好奇为什么直接在 var 上打印内存地址有效,但尝试通过接口执行相同操作却不能打印出内存地址?
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)
}
【问题讨论】:
-
在这种情况下,您应该使用
reflect包。reflect.ValueOf(&ad).Pointer()将返回 &ad(它是一个指针值)为uintptr。 -
谢谢,刚刚查了反映,现在正在阅读反射定律。
标签: pointers memory go struct interface