【问题标题】:Golang: interface func to print memory addressGolang:打印内存地址的接口函数
【发布时间】: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)
}

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

【问题讨论】:

  • 在这种情况下,您应该使用reflect 包。 reflect.ValueOf(&ad).Pointer() 将返回 &ad(它是一个指针值)为 uintptr
  • 谢谢,刚刚查了反映,现在正在阅读反射定律。

标签: pointers memory go struct interface


【解决方案1】:

因为在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[]

如果您修改该行以打印address.a 类型为int 的字段的地址:

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

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

a's memory address -->  0x1040e13c

【讨论】:

  • 我进行了您建议的更改,它们的工作方式完全符合我的要求,也感谢您的简洁回答。
猜你喜欢
  • 2014-05-13
  • 1970-01-01
  • 2019-02-22
  • 1970-01-01
  • 1970-01-01
  • 2017-02-21
  • 1970-01-01
  • 2019-02-03
  • 1970-01-01
相关资源
最近更新 更多