英文:
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)
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论