0
package main

import "fmt"

type Employee struct {
    ID int
    Name string
}

func main(){
    var zhexiao Employee
    zhexiao.Name = "xiao"
    fmt.Println(&zhexiao)

    x := 1
    p := &x
    fmt.Println(p)
}

The above code outputs two kinds of pointers.

  1. struct pointer output is: &{0 xiao}
  2. integer pointer output is: 0xc0420600b0 (it looks like a memory address)

Why struct pointer output is not a memory address? If it's not memory address, what is it?

Thanks a lot Zhe

peterSO
  • 158,998
  • 31
  • 281
  • 276
Zhe Xiao
  • 454
  • 1
  • 3
  • 9
  • fmt.Println is not suitable to inspect the internals. Read the language spec. – Volker Jun 29 '18 at 04:51
  • 1
    Possible duplicates: [How does a pointer to a struct or array value in Go work?](https://stackoverflow.com/questions/51018357/how-does-a-pointer-to-a-struct-or-array-value-in-go-work/51018395#51018395); and [Difference between golang pointers](https://stackoverflow.com/questions/42039827/difference-between-golang-pointers/42042673#42042673). – icza Jun 29 '18 at 07:49

1 Answers1

7

It depends on how you look at it. You are implicitly using the package fmt default print verb (%v). Here are some other ways to look at it by explicitly using other print verbs.

package main

import "fmt"

type Employee struct {
    ID   int
    Name string
}

func main() {
    var zhexiao Employee
    zhexiao.Name = "xiao"
    fmt.Printf("%[1]v %[1]p\n", &zhexiao)

    x := 1
    fmt.Printf("%[1]v %[2]p\n", x, &x)
    p := &x
    fmt.Printf("%[1]v %[1]p\n", p)
}

Playground: https://play.golang.org/p/4dV8HtiS8rP

Output:

&{0 xiao} 0x1040a0d0
1 0x1041402c
0x1041402c 0x1041402c

Reference: Package fmt: Printing

peterSO
  • 158,998
  • 31
  • 281
  • 276