ds753947 2016-09-28 06:37
浏览 353
已采纳

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

I am curious as to why just printing the memory address on a var directly works but trying to do the same action through an interface doesn't print out the memory address?

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

Just wanted to add this after fixing errors, it now functions as expected. Testing shifting memory pointers

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

  • 写回答

1条回答 默认 最新

  • dongya6381 2016-09-28 06:56
    关注

    Because in your second case inside the memory() method:

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

    ad is not an int but a struct, ad is of type address. And you're not printing the address of an int but an address of a struct. And the default formatting for pointer to a struct is: &{}.

    Quoting from package doc of fmt regarding default formats:

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

    If you modify the line to print the address of the address.a field which is of type int:

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

    You will see the same pointer format printed in hexadecimal format, e.g.:

    a's memory address -->  0x1040e13c
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 关于#matlab#的问题:在模糊控制器中选出线路信息,在simulink中根据线路信息生成速度时间目标曲线(初速度为20m/s,15秒后减为0的速度时间图像)我想问线路信息是什么
  • ¥15 banner广告展示设置多少时间不怎么会消耗用户价值
  • ¥16 mybatis的代理对象无法通过@Autowired装填
  • ¥15 可见光定位matlab仿真
  • ¥15 arduino 四自由度机械臂
  • ¥15 wordpress 产品图片 GIF 没法显示
  • ¥15 求三国群英传pl国战时间的修改方法
  • ¥15 matlab代码代写,需写出详细代码,代价私
  • ¥15 ROS系统搭建请教(跨境电商用途)
  • ¥15 AIC3204的示例代码有吗,想用AIC3204测量血氧,找不到相关的代码。