我很好奇为什么只是在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)
}
答案 0 :(得分:2)
因为在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[]
如果您修改该行以打印类型为address.a
的{{1}}字段的地址:
int
您将看到以十六进制格式打印的相同指针格式,例如:
fmt.Println("a's memory address --> ", &ad.a)