Comparison operators in Go are designed to compare two values, helping determine their relational connection. They return a Boolean result of either true
(1) or false
(0), depending on whether the comparison holds.
Using a Comparison Operator
The greater-than operator (>
) is one such example. It checks whether one value is larger than another.
Go
x
package main
import "fmt"
func main() {
var yamaha = 5
var suzuki = 3
fmt.Println(yamaha > suzuki) // returns true because 5 is greater than 3
}
List of Comparison Operators in Go
Here’s a table listing all comparison operators, their meanings, and examples:
Operator | Name | Example |
---|---|---|
== | Equal to | x == y |
!= | Not equal | x != y |
> | Greater than | x > y |
< | Less than | x < y |
>= | Greater than or equal to | x >= y |
<= | Less than or equal to | x <= y |
Examples Using Comparison Operators
Here’s a practical implementation showcasing various comparison operators:
Go
package main
import "fmt"
func main() {
var ducati = 10
var honda = 8
var yamaha = 10
// Equal to
fmt.Println(ducati == yamaha) // true, as both are 10
// Not equal
fmt.Println(ducati != honda) // true, as 10 is not equal to 8
// Greater than
fmt.Println(ducati > honda) // true, as 10 is greater than 8
// Less than
fmt.Println(honda < yamaha) // true, as 8 is less than 10
// Greater than or equal to
fmt.Println(ducati >= yamaha) // true, as 10 is equal to 10
// Less than or equal to
fmt.Println(honda <= ducati) // true, as 8 is less than 10
}