Comparing Structs of Different Types
When comparing two structs of different types, Go raises a compile-time error. Consider the example below where we define two separate struct types, s1 and s2, each containing an integer field x. In the code, we create an instance of each type and attempt to compare them using the equality operator.Attempting to compare struct instances of different types (s1 and s2) results in the error:
“Invalid operation: c == c1 (mismatched types s1 and s2)”.
Ensure that both structs are of the same type before comparing them.
“Invalid operation: c == c1 (mismatched types s1 and s2)”.
Ensure that both structs are of the same type before comparing them.
Comparing Structs of the Same Type
Next, let’s examine how to compare struct variables when they belong to the same type. In this example, we define a single struct type, s1, and create three variables in the main function. Variables c and c2 are initialized with the same value (5) while c1 is assigned a different value (6). The code then demonstrates both inequality and equality checks.Summary
In this lesson, you learned how to compare structs in Go, covering the following key points:- Struct equality operators (== and !=) can only be utilized if both operands are of the same type.
- Comparing structs of different types will result in a compile-time error.
- When comparing structs of the same type, all corresponding fields must hold equal values for the structs to be considered equal.
Experiment with these examples to solidify your understanding of struct comparisons in Go. For further learning, explore additional Go concepts in the Go Documentation.