How to compare the equality of structures in golang

if the object is created by the same struct without complex type can be directly used by == on the ratio and pointer

Simple type

sortable data type

Integer
Floating point
String

data type that can be compared

in addition to the above three, there are
Boolean,
Complex,
Pointer,
Channel,
Interface
Array

complex non-comparable data type

Slice
Map
Function

as follows

type User struct {
	age  int
	name string
}

func main() {
	user := User{
		1,
		"d",
	}
	user2 := User{
		1,
		"d",
	}
	fmt.Println(user == user2)  //打印的结果是true 会去自动对比内部的属性是否相等
	//但是如果结构体内部含有map,slice,Function 使用==比较编译会报错
}

the == operator
example

can be used if two objects that are not created in the same structure can be converted to each other and do not contain non-comparable member variables

type USER struct {
	age  int
	name string
	u    Name
}
type Name struct {
	a string
}
type USER2 struct {
	age  int
	name string
	u    Name
}

func main() {
	user := USER{
		1,
		"d",
		Name{""},
	}
	user3 := USER2{
		1,
		"d",
		Name{""},
	}
	user2 := USER(user3)
	fmt.Println(user2 == user) //编译通过 打印结果是true
}

refer to official document

Read More: