我很好奇为什么直接在 var 上打印内存地址有效,但尝试通过接口(interface)执行相同的操作却无法打印出内存地址?
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)
}
最佳答案
因为在 memory()
方法中的第二种情况:
func (ad address) memory() {
fmt.Println("a - ", ad)
fmt.Println("a's memory address --> ", &ad)
}
ad
不是int
而是一个结构,ad
是address
类型。您打印的不是 int
的地址,而是 struct
的地址。指向结构的指针的默认格式为:&{}
。
引用自 fmt
的包文档关于默认格式:
struct: {field0 field1 ...} array, slice: [elem0 elem1 ...] maps: map[key1:value1 key2:value2] pointer to above: &{}, &[], &map[]
如果您修改该行以打印类型为 int
的 address.a
字段的地址:
fmt.Println("a's memory address --> ", &ad.a)
您将看到以十六进制格式打印的相同指针格式,例如:
a's memory address --> 0x1040e13c
关于pointers - 戈朗 : interface func to print memory address,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39739743/