
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Compare Slices, Structs, and Maps in Golang
The reflect package in Go provides a very important function called DeepEqual() which can be used to compare composite types. The DeepEqual() function is used when we want to check if two data types are "deeply equal".
Comparing slices
Example 1
Consider the code shown below
package main import ( "fmt" "reflect" ) func main() { sl := []int{1, 2, 3} sl1 := []int{1, 2, 3} fmt.Println(reflect.DeepEqual(sl, sl1)) }
Output
If we run the command go run main.go on the above code, then we will get the following output in the terminal.
true
Comparing maps
Example 2
Consider the code shown below.
package main import ( "fmt" "reflect" ) func main() { m1 := make(map[string]int) m1["rahul"] = 10 m1["mukul"] = 11 m2 := make(map[string]int) m2["rahul"] = 10 m2["mukul"] = 11 fmt.Println(reflect.DeepEqual(m1, m2)) }
Output
If we run the command go run main.go on the above code, then we will get the following output in the terminal.
true
Comparing structs
Example 3
Consider the code shown below.
package main import ( "fmt" "reflect" ) type Person struct { name string age int } func main() { p1 := Person{name: "TutorialsPoint", age: 10} p2 := Person{name: "TutorialsPoint", age: 10} fmt.Println(reflect.DeepEqual(p1, p2)) }
Output
If we run the command go run main.go on the above code, then we will get the following output in the terminal.
true
Advertisements