golang

Golang Comparable Examples

One of the fundamental concepts in Golang is comparability which allows for the comparison and order of values of certain types. Comparability is a property that determines whether two values of a particular type can be compared or ordered. In this article, we will explore the Go idea of comparison while looking at plenty of useful examples for it.

Example 1: Compare the String in Golang

Begin with the string comparison in Go. We can compare two strings using the “strings.Compare()” function. An integer value that indicates the connection between the two strings is the result of the strings.Compare() function.

package main
import (
    "fmt"
    "strings"
)
func main() {
    Greater:= strings.Compare("V", "A")
    Lesser:= strings.Compare("A", "V")
    fmt.Println(Greater)
    fmt.Println(Lesser)
}

Here, we compare the “V” and “A” strings using the strings.Compare(“V”, “A”), and store the result in the “Greater” variable. Similarly, we compare the “A” and “V” strings using the strings.Compare(“A”, “V”), and store the result in the “Lesser” variable. Finally, we print the values of the “Greater” and “Lesser” variables using fmt.Println(). In our case, “V” is greater than “A”, so “Greater” is assigned the value of 1. And “A” is less than “V”, so “Lesser” is assigned the value of -1.

The resultant integer values are displayed in the following output:

Example 2: Compare the Byte Slice in Golang

Next, we use the bytes to carry out the comparisons between the byte slices. The byte slices are compared for equality using the Equal() method.

package main
import (
    "bytes"
    "fmt"
)
func main() {
    s1 := []byte{2, 4, 6, 8, 10}
    s2 := []byte{2, 4, 6, 8, 10}
    s3 := []byte{10, 8, 6, 4, 2}
    fmt.Println(bytes.Equal(s1, s2))
    fmt.Println(bytes.Equal(s1, s3))
}

Here, we use the bytes.Equal() function to compare two byte slices ([]byte). Before that, we declare and initialize three slices. The “s1” contains the 2, 4, 6, 8, and 10 elements in that order. The “s2” also contains the 2, 4, 6, 8, and 10 elements in the same order as s1. While s3 contains the same elements as “s1”, but in reverse order. Then, the bytes.Equal(s1, s2) is employed which compares s1 with s2. This comparison checks if the two slices are equal. The bytes.Equal(s1, s3) is called again to compare s1 with s3. This comparison also checks if the two slices are equal. However, s3 has the same elements as s1, but in reverse order.

Since s1 and s2 have the same elements in the same order, the output generates true. Whereas the false value indicates that the slices are not equal.

Example 3: Compare the Time in Golang

However, the time can also be compared using the time package in Go. The following is the code that is provided to compare the different times:

package main
import (
   "fmt"
   "time"
)
func main() {
   time1 := time.Date(2023, time.June, 11, 15, 20, 0, 0, time.UTC)
   time2 := time.Date(2023, time.June, 11, 16, 0, 0, 0, time.UTC)
   if time1.Before(time2) {
      fmt.Println("time1 is before time2")
   } else if time1.After(time2) {
      fmt.Println("time1 is after time2")
   } else {
      fmt.Println("time1 and time2 are equal")
   }
}

Begin with the main() function where we declare and initialize the  two-time values. Both time values are created using the time.Date() function which takes the year, month, day, hour, minute, second, nanosecond, and location (in this case, we use the time.UTC) as parameters. After that, we use the “if” statement to compare the time values using the Before() and After() methods of the “time.Time” type. Here, the “time1.Before(time2)” checks if time1 occurs before time2. On the other hand, “time1.After(time2)” checks if time1 occurs after time2.

The output represents the results where time1 occurs before time2 since the first condition evaluates to true:

Example 4: Compare the Maps in Golang

Additionally, we can compare two maps in Go to check if they are equal. Let’s consider the comparison among the maps in the following:

package main
import (
   "fmt"
)
func main() {
   map1 := map[string]string{"fruit": "apple", "vegetable": "carrot"}
   map2 := map[string]string{"fruit": "apple", "vegetable": "carrot""}
   if len(map1) != len(map2) {
      fmt.Println("
map1 and map2 are not equal")
      return
   }

   for key, val := range map1 {
      if map2[key] != val {
         fmt.Println("
map1 and map2 are not equal")
         return
      }
   }
   fmt.Println("
map1 and map2 are equal")
}

Here, we declare the “map1” variable which is a map of the “map[string]string” type with the “fruit” and “vegetable” keys and corresponding string values of “apple” and “carrot”. Similarly, we declare the “map2” variable which is also a map of the “map[string]string” type with the same keys and values as map1. After that, with the usage of the “if” statement, we check if the lengths of map1 and map2 are equal. If they are not equal, it means that the maps have a different number of key-value pairs. Therefore, they are not equal.

Next, we use a for-loop that iterates over the key-value pairs in map1 to examine whether the length of the specified maps is equal or not. Inside the loop, it compares the corresponding values in map2 using the same key. Moreover, if the loop completes without returning, it means that all key-value pairs are checked and are found to be equal.

Since the provided maps have the same key-value pairs, the following output shows that they are equal:

Example 5: Compare the Structures in Golang

Similarly, the struct fields in Golang can be compared one by one. Comparing the struct instances for equality requires comparing each field of the struct.

package main

import (
   "fmt"
)
type Employee struct {
   Name string
   Age  int
}
func main() {
   e1 := Employee{Name: "Matty", Age: 28}
   e2 := Employee{Name: "Matty", Age: 28}
   if e1 == e2 {
      fmt.Println("e1 and e2 are equal")
   } else {
      fmt.Println("e1 and e2 are not equal")
   }
}

Here, two fields—Name, of type text, and Age, of type int—are defined for the “Employee” struct. The comparison is made between two instances of the “Employee” struct – e1 and e2 – which are created in the main() function. Then, we compare e1 and e2 using the “==” operator.

In Go, the “==” operator can be used to compare the structs directly. When comparing two structs, it checks if all the corresponding fields in the two structs are equal. If all the fields are equal, the comparison evaluates to true. Otherwise, it evaluates to false. In this case, e1 and e2 have the same values for both the “Name” and “Age” fields. Therefore, the e1 == e2 comparison evaluates to true.

The output retrieves the following results which displays that both the e1 and e2 instances are equal:

Example 6: Compare the Interfaces in Golang

We go with another case of the Golang comparison where we compare the interfaces to check the equality.

package main
import "fmt"
type person interface {
    study()
    eat()
}
type student struct {
    age int
}
func (s student) study() {
    fmt.Println("Student studies")
}
func (s student) eat() {
    fmt.Println("Student eats")
}
func main() {
    var x person
    var y person
    var z person
    var k person
    var m person
    x = student{age: 18}
    y = student{age: 18}
    z = student{age: 16}
    if x == y {
        fmt.Println("x and y are equal")
    } else {s
        fmt.Println("x and y are not equal")
    }
    if x == z {
        fmt.Println("x and z are equal")
    } else {
        fmt.Println("x and z are not equal")
    }
    if k == m {
        fmt.Println("k and m are equal")
    } else {
        fmt.Println("k and m are not equal")
    }
}

First, we define the study() and eat() methods for the “student” struct to satisfy the person interface. Then, within the main() function, we compare the different instances of a student based on the person interface type. Next, the “student” struct is employed with an “age” field. It implicitly implements the person interface because it implements both the study() and eat() methods. The study() method of the “student” struct prints the “Student studies” and the eat() method prints the “Student eats”.

After that, we declare the x, y, and z variables and assign the “student” structs, each with a different age. The “if” statement is used to figure out whether the provided variables are equal. Since both “k” and “m” are uninitialized and hold the “nil” values, the output is “k and m are not equal”.

The output is fetched in the following as expected from the previous source code:

Conclusion

We explored the different examples of Golang comparable which are executable. Understanding the comparability in Golang empowers the creation of more efficient and robust programs that leverage the power of sorting and comparison.

About the author

Kalsoom Bibi

Hello, I am a freelance writer and usually write for Linux and other technology related content