pointers - 戈朗 : interface func to print memory address

标签 pointers memory go struct interface

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

相关文章:

c - strchr() 非 const 的返回类型?

c - 在链表上插入一个新节点会创建一个新节点

c++ - 将多个相同类型的指针添加到 vector

我是否仍可以对具有第二个 malloc() 调用的变量调用 free()?

go - 如何使用 jwt-go 库验证 JSON Web Token?

检查整个数组中数字的频率

c# - 无法定位 Android 应用中内存泄漏的原因

php - 耗尽内存 - 尝试修复循环,仍然不起作用

opencv - 在 Go 应用程序中查找内存泄漏

google-app-engine - 没有路由器 Gorilla Mux 的 Google Cloud Go 处理程序?