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

时间:2019-05-13 12:23:37

标签: pointers go struct

我是新手,我想在go中打印struct变量的地址 这是我的程序

type Rect struct {
 width int
 name int 
}

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

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

}

此输出

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

但是我想打印r变量的地址,因为我知道'&'表示地址,'*'指向指针位置的值,但是在这里我无法打印r的地址,我正在使用在线编辑器go-lang https://play.golang.org/

我也想将此地址存储在某个变量中。

1 个答案:

答案 0 :(得分:3)

使用fmt.Println()打印值时,将使用默认格式。引用fmt软件包的文档:

  

%v的默认格式为:

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
     

对于复合对象,使用以下规则递归地打印元素,如下所示:

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

结构值的地址是最后一行,因此它被特殊对待,因此使用&{}语法打印。

如果要打印其地址,请不要使用默认格式,而要使用格式字符串,并使用%p动词指定您想要的地址(指针):

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

这将输出(在Go Playground上尝试):

0x414020