结构体的内存地址不可见

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

Memory address for struct not visible

问题

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

  1. package main
  2. import "fmt"
  3. type stud struct {
  4. name string
  5. school string
  6. }
  7. func main() {
  8. stud1 := stud{"name1", "school1"}
  9. a := 10
  10. fmt.Println("&a is:", &a)
  11. fmt.Println("&stud1 is:", &stud1)
  12. }

输出结果为:

  1. &a is: 0x20818a220
  2. &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:

  1. package main
  2. import "fmt"
  3. func main() {
  4. stud1 := stud{"name1", "school1"}
  5. a:=10
  6. fmt.Println("&a is:", &a)
  7. fmt.Println("&stud1 is:",&stud1)
  8. }

output is:

  1. &a is: 0x20818a220
  2. &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

  1. 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.

  1. 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:

确定