结构体的内存地址不可见

huangapple go评论104阅读模式
英文:

Memory address for struct not visible

问题

在Go语言中,可以获取变量(如int)的内存地址,但不能获取结构体的内存地址。以一个示例来说明:

package main

import "fmt"

type stud struct {
    name   string
    school string
}

func main() {
    stud1 := stud{"name1", "school1"}
    a := 10
    fmt.Println("&a is:", &a)
    fmt.Println("&stud1 is:", &stud1)
}

输出结果为:

&a is: 0x20818a220
&stud1 is: &{name1 school1}

为什么&a会给出内存地址,而&stud1没有给出确切的内存位置呢?我并没有打算使用内存地址,只是对这种不同的行为感到好奇。

英文:

In Go, I was confused about why the memory address for variables like int can be obtained but not for structs. As an example:

package main

import "fmt"

func main() {
stud1 := stud{"name1", "school1"}
a:=10
fmt.Println("&a is:", &a)
fmt.Println("&stud1 is:",&stud1)
}

output is:

&a is: 0x20818a220
&stud1 is: &{name1 school1}

Why is &a giving the memory address, however &stud1 not giving the exact memory location. I don't have any intention of using the memory address but just was curious about the different behavior.

答案1

得分: 7

fmt 包使用反射来打印值,并且有一个特殊情况可以将指向结构体的指针打印为 &{Field Value}

如果你想要看到内存地址,可以使用指针格式化动词 %p

fmt.Printf("&stud is: %p\n", &stud)
英文:

the fmt package uses reflection to print out values, and there is a specific case to print a pointer to a struct as &{Field Value}.

If you want to see the memory address, use the pointer formatting verb %p.

fmt.Printf("&stud is: %p\n", &stud)

huangapple
  • 本文由 发表于 2015年4月8日 02:16:01
  • 转载请务必保留本文链接:https://go.coder-hub.com/29498374.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定