I have a basic question on empty struct
s and am trying to get my head around the following different outputs I am getting when attempting to get the address of backing arrays' elements for two slices:
a := make([]struct{}, 10)
b := make([]struct{}, 20)
fmt.Println("&a == &b", &a == &b)
fmt.Println("&a[0] == &b[0]", &a[0] == &b[0])
The above snippet returns:
&a == &b false
&a[0] == &b[0] true
However, considering the following slightly changed snippet:
a := make([]struct{}, 10)
b := make([]struct{}, 20)
fmt.Println(a[0], &a[0])
fmt.Println("&a == &b", &a == &b)
fmt.Println("&a[0] == &b[0]", &a[0] == &b[0])
The above snippet returns:
{} &{}
&a == &b false
&a[0] == &b[0] false
Can someone please explain the reason for the above difference? Thank you!
[Follow Up] Making the following modifications:
package main
import "fmt"
type S struct{}
func (s *S) addr() { fmt.Printf("%p
", s) }
func main() {
a := make([]S, 10)
b := make([]S, 20)
fmt.Println(a[0], &a[0])
fmt.Println("&a == &b", &a == &b)
fmt.Println("&a[0] == &b[0]", &a[0] == &b[0])
//a[0].addr()
//b[0].addr()
}
Still returns the same output:
{} &{}
&a == &b false
&a[0] == &b[0] false
Though, uncommenting the method calls, returns:
{} &{}
&a == &b false
&a[0] == &b[0] true
0x19583c // ==> [depends upon env]
0x19583c // ==> [depends upon env]
See Question&Answers more detail:
os