We can compare two structs in two ways:
1. Equal to (==) Operator
2. DeepEqual() Method in reflect package
Example using (==) Operator :
package main import "fmt" type User struct { name string age int } func main() { u1 := User{"tejas", 23} u2 := User{"tejas", 23} u3 := User{"vicky", 22} fmt.Println("Comparing u1 and u2 struct :", u1 == u2) fmt.Println("Comparing u1 and u3 struct :", u1 == u3) }
Output:
Comparing u1 and u2 struct : true
Comparing u1 and u3 struct : false
Example using DeepEqual() Method :
package main import ( "fmt" "reflect" ) type User struct { name string age int } func main() { u1 := User{"tejas", 23} u2 := User{"tejas", 23} u3 := User{"vicky", 22} fmt.Println("Comparing u1 and u2 struct :", reflect.DeepEqual(u1, u2)) fmt.Println("Comparing u1 and u3 struct :", reflect.DeepEqual(u1, u3)) }
Output:
Comparing u1 and u2 struct : true
Comparing u1 and u3 struct : false
Comments
Post a Comment