- Author

- Name
- Nelson Silva
- Social
Introduction
Comparison operators are fundamental to any programming language, as they allow the creation of conditions for decision-making. In Go, comparison operators are simple yet powerful.
Basic Operators
Here are the basic comparison operators you will find in Go:
==: Checks if two values are equal.!=: Checks if two values are different.>: Checks if the value on the left is greater than the value on the right.<: Checks if the value on the left is less than the value on the right.>=: Checks if the value on the left is greater than or equal to the value on the right.<=: Checks if the value on the left is less than or equal to the value on the right.
In addition, Go also has logical operators that are frequently used in combination with comparison operators:
&&: Represents the logical AND operator.||: Represents the logical OR operator.
Usage Examples
See the comparison operators in action:
package main
import "fmt"
func main() {
age := 28
if age >= 18 {
fmt.Println("You are of legal age.")
} else {
fmt.Println("You are underage.")
}
}
// You are of legal age.
Comparing Strings
In Go, it is also possible to use comparison operators for strings. This allows comparing two strings in lexicographic order.
name1 := "Ana"
name2 := "John"
if name1 < name2 {
fmt.Println(name1, "comes before", name2)
} else {
fmt.Println(name2, "comes before", name1)
}
// Ana comes before John
Important Tips
- Compatible Types: When comparing two values in Go, they must be of compatible types. For example, it is not possible to directly compare an int with a float64.
- Avoid Comparing Floats Directly: Due to precision and the way floats are stored, it may not be safe to directly compare two floating-point numbers. Instead, consider using an approach that accounts for a small margin of error.
Conclusion
Comparison operators are essential tools in Go and in any other programming language. They are the foundation for decision-making and control flow in programs.