gpt4 book ai didi

pointers - 戈朗 : interface func to print memory address

转载 作者:IT王子 更新时间:2023-10-29 02:03:58 24 4
gpt4 key购买 nike

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

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 而是一个结构,adaddress 类型。您打印的不是 int 的地址,而是 struct 的地址。指向结构的指针的默认格式为:&{}

引用自 fmt 的包文档关于默认格式:

struct:             {field0 field1 ...}
array, slice: [elem0 elem1 ...]
maps: map[key1:value1 key2:value2]
pointer to above: &{}, &[], &map[]

如果您修改该行以打印类型为 intaddress.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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com