douping6871 2019-05-13 12:23
浏览 3126
已采纳

如何在Go中打印结构变量的地址

I am new to go I want to print the address of struct variable in go here is my program

type Rect struct {
 width int
 name int 
}

func main() {
 r := Rect{4,6}
 p := &r
 p.width = 15

fmt.Println("-----",&p,r,p,&r)

}

output of this

  _____0x40c130 {15 6} &{15 6} &{15 6}

but i want to print the address of r variable as i know that '&' represents the address and '*' points the value of pointer location but here i am unable to print the address of r, I am using online editor of go-lang https://play.golang.org/

As well I want to store this address in some variable.

  • 写回答

1条回答 默认 最新

  • dsfh40613182 2019-05-13 12:28
    关注

    When you print values using fmt.Println(), the default format will be used. Quoting from package doc of fmt:

    The default format for %v is:

    bool:                    %t
    int, int8 etc.:          %d
    uint, uint8 etc.:        %d, %#x if printed with %#v
    float32, complex64, etc: %g
    string:                  %s
    chan:                    %p
    pointer:                 %p
    

    For compound objects, the elements are printed using these rules, recursively, laid out like this:

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

    The address of a struct value is the last line, so it is treated special and thus printed using the &{} syntax.

    If you want to print its address, don't use the default format, but use a format string and specify you want the address (pointer) explicitly with the %p verb:

    fmt.Printf("%p
    ", &r)
    

    This will output (try it on the Go Playground):

    0x414020
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值
  • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
  • ¥15 CSAPPattacklab
  • ¥15 一直显示正在等待HID—ISP
  • ¥15 Python turtle 画图
  • ¥15 关于大棚监测的pcb板设计
  • ¥15 stm32开发clion时遇到的编译问题
  • ¥15 lna设计 源简并电感型共源放大器
  • ¥15 如何用Labview在myRIO上做LCD显示?(语言-开发语言)
  • ¥15 Vue3地图和异步函数使用