SoFunction
Updated on 2025-03-02

A detailed explanation of the object of Go's advanced feature exploration

How to compare two go objects exactly the same

In go language, to compare whether two objects are exactly the same, we can use the following three methods:

Method 1: Use

It is a built-in depth comparison function in Go language. It can recursively compare values ​​of any type, including structures, slices, maps, etc.

import (
    "reflect"
)
func main() {
    a := []int{1, 2, 3}
    b := []int{1, 2, 3}
    equal := (a, b)
    (equal) // true
}

However, it should be noted that when using the comparison struct type, it is necessary to ensure that the order and type of the fields in the structure body are exactly the same. Otherwise, the comparison results will be incorrect. Here is an example of error:

import (
    "reflect"
)
 type person struct {
    Name string
    Age int
}
func main() {
    a := person{Name: "Alice", Age: 18}
    b := person{Age: 18, Name: "Alice"}
    equal := (a, b)
    (equal) // false
}

In the above example, the fields of structures a and b are in different order, resulting in the comparison result being false.

Method 2: Serialization using

We can use serializing two objects into JSON strings and then comparing whether the two strings are equal to determine whether the two objects are exactly the same.

import (
    "encoding/json"
)
type person struct {
    Name string
    Age int
}
func main() {
    a := person{Name: "Alice", Age: 18}
    b := person{Name: "Alice", Age: 18}
    aa, _ := (a)
    bb, _ := (b)
    equal := string(aa) == string(bb)
    (equal) // true
}

It should be noted that when using this method to compare struct types, the field types in struct must be of type supported by json, otherwise serialization comparison cannot be performed. At the same time, using this method is relatively inefficient.

Method 3: Recursive comparison

We can directly write recursive functions to compare whether the two objects are exactly the same, which can ensure support for various types, which is more flexible and efficient.

Here is an example of a recursive comparison:

import (
    "reflect"
)
func IsEqual(a, b interface{}) bool {
    if (a, b) {
        return true
    }
    va, vb := (a), (b)
    if () != () {
        return false
    }
    switch () {
    case :
        return IsEqual(().Interface(), ().Interface())
    case , :
        if () != () {
            return false
        }
        for i := 0; i < (); i++ {
            if !IsEqual((i).Interface(), (i).Interface()) {
                return false
            }
        }
        return true
    case :
        if () != () {
            return false
        }
        for _, key := range () {
            if !IsEqual((key).Interface(), (key).Interface()) {
                return false
            }
        }
        return true
    case :
        for i := 0; i < (); i++ {
            if !IsEqual((i).Interface(), (i).Interface()) {
                return false
            }
        }
        return true
    default:
        return false
    }
}
type person struct {
    Name string
    Age int
}
func main() {
    a := []person{{"Alice", 18}, {"Bob", 20}}
    b := []person{{"Alice", 18}, {"Bob", 20}}
    equal := IsEqual(a, b)
    (equal) // true
}

In recursive comparison functions, the judgment and comparison methods for various types are different, and they need to be written according to actual conditions. When using this method, please ensure the correctness of the recursive function, otherwise the comparison result will be incorrect.

Examples of use in the project

In actual projects, it may be necessary to compare whether some complex objects are exactly the same. For example, in an e-commerce system, it may be necessary to compare whether two orders are exactly the same. Here is a code example for an order comparison:

type order struct {
    ID string
    Items []item
    Account string
    Price float64
}
type item struct {
    Name string
    Price float64
    Count int
}
func (o *order) Equal(other *order) bool {
    if o == other {
        return true
    }
    if  !=  ||  !=  ||  !=  {
        return false
    }
    if len() != len() {
        return false
    }
    for i := range  {
        if ![i].Equal(&[i]) {
            return false
        }
    }
    return true
}
func (i *item) Equal(other *item) bool {
    return  ==  &&  ==  &&  == 
}

In the above code, we define an Equal method in which we compare whether each item in the order ID, account number, price and product list is the same.

Open source project example

Open source projects often involve the issue of comparing whether the objects are exactly the same. Here are some of the more popular open source projects to compare:

Kubernetes

ObjectMeta structure is defined in Kubernetes, which contains fields such as Name, Namespace, Labels, etc.

type ObjectMeta struct {
    Name string `json:"name,omitempty"`
    Namespace string `json:"namespace,omitempty"`
    Labels map[string]string `json:"labels,omitempty"`
    Annotations map[string]string `json:"annotations,omitempty"`
}

In order to compare whether the two objects are the same, the Equal method is overloaded in Kubernetes, the code is as follows:

func (a *ObjectMeta) Equal(b *ObjectMeta) bool {
    if a == nil && b == nil {
        return true
    }
    if a == nil || b == nil {
        return false
    }
    return  ==  &&  ==  && (, ) && (, )
}

In the Equal method, determine whether all fields of the two objects are the same.

Etcd

Etcd is a distributed key-value storage system for shared configuration and service discovery. In Etcd, a structure is defined to compare whether two values ​​are equal.

type Compare struct {
    Target Operand
    Result Result
    Order  Comparison
}
type Operand interface {
    Descriptor() ([]byte, []int)
}
type Result interface {
    Descriptor() ([]byte, []int)
}
type Comparison int32
const (
    Comparison_EQUAL    Comparison = 0
    Comparison_GREATER  Comparison = 1
    Comparison_LESS     Comparison = 2
    Comparison_GREATER_EQUAL Comparison = 3
    Comparison_LESS_EQUAL    Comparison = 4
)

In the Compare structure, we can see three fields that represent the value to be compared, the comparison result and the comparison method. When the comparison method is the same, only if the values ​​to be compared and the comparison result are exactly the same, can the two objects be considered to be exactly the same.

Summarize

We can use various methods such as recursive comparison to compare whether two objects are exactly the same. At the same time, in actual projects and open source projects, corresponding comparison methods are also needed to be written based on actual conditions to ensure the correctness and readability of the code.

The above is a detailed explanation of the objects that explore Go advanced features. For more information about Go object comparison, please pay attention to my other related articles!