Golang:界面函数来打印内存地址

我很好奇为什么只在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)

}

https://play.golang.org/p/BnB14-yX8B

回答:

因为在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类型的字段的地址int

fmt.Println("a's memory address --> ", &ad.a)

您将看到以十六进制格式打印的相同指针格式,例如:

a's memory address -->  0x1040e13c

以上是 Golang:界面函数来打印内存地址 的全部内容, 来源链接: utcz.com/qa/417325.html

回到顶部