Help us understand the problem. What is going on with this article?

golang struct の比較

More than 3 years have passed since last update.

structの比較はどのようにするのが良いのかわからなかったので色々実験してみた

結論

保持するパラメータで比較: *object1 == *object2
hashで比較: object1 == object2
で良さそう。

実験コード

https://play.golang.org/p/3gB26JkPMm

package main

type parent struct {
    name  string
    param int
    child
}

type child struct {
    name  string
    param int
}

func main() {
    childName := "foo"
    childParam := 1
    child1 := child{name: childName, param: childParam}
    child2 := &child{name: childName, param: childParam}

    println("###################")
    println("&child1", &child1)
    println("child2", child2)
    println("&*child2", &*child2)
    println("&child2", &child2)
    println("child equals result 1:", child1 == *child2)
    println("child equals result 2:", child1 == *&*child2)
    println("child equals result 3:", *&child1 == *child2)
    println("child equals result 4:", &child1 == *&child2)

    parentName := "tests"
    parentParam := 3
    parent1 := &parent{name: parentName, param: parentParam, child: child1}
    parent2 := &parent{name: parentName, param: parentParam, child: child1}

    println("###################")
    println(parent1)
    println(parent2)
    println("result:", *parent1 == *parent2)

}
Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away