dongya5893 2016-11-20 09:19 采纳率: 100%
浏览 18
已采纳

为什么struct上的&运算符不返回数字地址?

I just started to learn the golang.

I found the & operator behaves differently for simple type and struct.

  • For simple type, & returns an address.

  • For struct, it returns something else.

Code:

package main

import "fmt"

type person struct {
    name string
    age  int
}

func main() {
    s1 := "abc"
    fmt.Println("s1 address =", &s1)

    s2 := person{"Sam", 55}
    fmt.Println("s2 address = ", &s2)

}

Output:

[ `hello` | done: 79.0079ms ]
    s1 address = 0xc04203c1e0
    s2 address =  &{Sam 55}   <======== What's this? And why not some address like above?

Again, is this design a have-to or a happen-to?

  • 写回答

1条回答 默认 最新

  • dougang1967 2016-11-20 09:48
    关注

    The unitary operator & behaves the same for builtin types and structs, it's used to get the memory address of a var. In this case we'll see &{Sam 55} because Go always checks by default if the parameter in fmt.Println() is a struct or a pointer to struct and in that case will try to print each field of the struct for debugging purposes, but if you want to see a pointer you can use fmt.Printf() with %p, like this:

    func main() {
        s1 := "abc"
        fmt.Println("s1 address =", &s1)
    
        s2 := person{"Sam", 55}
    
        fmt.Println("s2 as pointer =", &s2)
    
        fmt.Printf("s2 address = %p value with fields %+v", &s2, s2)
    }
    

    Bonus: you can use %+v to print field names and values

    https://play.golang.org/p/p7OVRu8YWB

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

报告相同问题?

悬赏问题

  • ¥15 Vue3 大型图片数据拖动排序
  • ¥15 划分vlan后不通了
  • ¥15 GDI处理通道视频时总是带有白色锯齿
  • ¥20 用雷电模拟器安装百达屋apk一直闪退
  • ¥15 算能科技20240506咨询(拒绝大模型回答)
  • ¥15 自适应 AR 模型 参数估计Matlab程序
  • ¥100 角动量包络面如何用MATLAB绘制
  • ¥15 merge函数占用内存过大
  • ¥15 使用EMD去噪处理RML2016数据集时候的原理
  • ¥15 神经网络预测均方误差很小 但是图像上看着差别太大