'golang why comparing two variables pointing to struct behaves differently?

I have created two instances of same struct, Confused by the output when I compare two variables point to instances of struct.

package main

import "fmt"

type Person struct {
    name string
}

func main() {
   p1 := &Person{name: "guru"}
   p2 := &Person{name: "guru"}
   fmt.Println(p1 == p2) // false, compares by address?
   p3 := Person{name: "guru"}
   p4 := Person{name: "guru"}
   fmt.Println(p3 == p4) // true , why? compares by content?
}

does == operator works like overload operator?



Solution 1:[1]

Your first example

p1 := &Person{name: "guru"}
p2 := &Person{name: "guru"}

fmt.Println(p1 == p2) // false, compares by address?

compares two pointers for equality. Since they each address different memory addresses, the do not compare as equal.

Your second example,

 p3 := Person{name: "guru"}
 p4 := Person{name: "guru"}

fmt.Println(p3 == p4) // true , why? compares by content?

compares two struct and does so by value, so they compare equal.

If you dereference the pointer before the comparison, you'll find that they compare as equal. For instance, given

p1 := &Person{ name: "guru" }
p2 := &Person{ name: "guru" }
p3 :=  Person{ name: "guru" }
p4 :=  Person{ name: "guru" }

All of the following compare as equal:

  • *p1 == *p2
  • *p1 == p3
  • p3 == *p2
  • p3 == p4

Solution 2:[2]

Two pointers values are only equal when they point to the same value in the memory or if they are nil in Golang. You create two instances of struct, thus they have different address

   p1 := &Person{name: "guru"}
   p2 := &Person{name: "guru"}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Nicholas Carey
Solution 2 Alex