Structural equality in Golang
Structure or struct in Golang is a user-defined type that allows us to create a group of elements of different types into a single unit. Any real-world entity that has some properties or fields can be represented as a struct . This concept is often compared to classes in object-oriented programming. It can be called a compact class that does not support inheritance but supports composition.
In Go language, you are allowed to compare two structures if they are of same type and contain same field values with the help of == operator or DeeplyEqual() method . Both operator and method return true if structures are identical, otherwise, return false . And if the variables being compared belong to different structures, then compiler throws an error.
Let's look at an example to better understand equality or structural comparison in Golang !
Note: The DeeplyEqual() method is defined in the "reflect" package.
Example 1:
// Chương trình Go minh họa // khái niệm của so sánh bình đẳng cấu trúc // using == operator package main import "fmt" // Tạo một cấu trúc type Author struct { name string branch string language string Particles int } // Hàm chính func main() { // Tạo biến // của cấu trúc Author a1 := Author{ name: "Moana", branch: "CSE", language: "Python", Particles: 38, } a2 := Author{ name: "Moana", branch: "CSE", language: "Python", Particles: 38, } a3 := Author{ name: "Dona", branch: "CSE", language: "Python", Particles: 38, } // Kiểm tra xem a1 bằng // a2 hay không // Dùng toán tử == if a1 == a2 { fmt.Println("Variable a1 is equal to variable a2") } else { fmt.Println("Variable a1 is not equal to variable a2") } // Kiểm tra xem a1 bằng // a2 hay không // Dùng toán tử == if a2 == a3 { fmt.Println("Variable a2 is equal to variable a3") } else { fmt.Println("Variable a2 is not equal to variable a3") } } Result:
Variable a1 is equal to variable a2 Variable a2 is not equal to variable a3 Example 2:
// Chương trình Go minh họa // khái niệm bình đẳng cấu trúc // dùng phương thức DeepEqual() package main import ( "fmt" "reflect" ) // Tạo một cấu trúc type Author struct { name string branch string language string Particles int } // Hàm chính func main() { // Tạo biến // của cấu trúc Author a1 := Author{ name: "Soana", branch: "CSE", language: "Perl", Particles: 48, } a2 := Author{ name: "Soana", branch: "CSE", language: "Perl", Particles: 48, } a3 := Author{ name: "Dia", branch: "CSE", language: "Perl", Particles: 48, } // So sánh a1 với a2 // Dùng phương thức DeepEqual() fmt.Println("Is a1 equal to a2: ", reflect.DeepEqual(a1, a2)) // So sánh a2 với a3 // Dùng phương thức DeepEqual() fmt.Println("Is a2 equal to a3: ", reflect.DeepEqual(a2, a3)) } Result:
Is a1 equal to a2: true Is a2 equal to a3: false