Relational operators help us compare two values to see how they relate to each other, like if one is bigger or equal to the other.
0
0
Relational operators in Go
Introduction
Checking if a number is greater than another to decide what to do next.
Comparing user input to a stored password length for validation.
Finding out if two values are equal to trigger a special action.
Determining if a score is less than a passing mark to show a message.
Seeing if a value is not equal to something to handle exceptions.
Syntax
Go
value1 <operator> value2 // Operators: // == (equal to) // != (not equal to) // > (greater than) // < (less than) // >= (greater than or equal to) // <= (less than or equal to)
Relational operators always compare two values and return a boolean: true or false.
They are often used inside if statements or loops to control the program flow.
Examples
Checks if a is equal to b.
Go
a == b
Checks if score is greater than or equal to 50.
Go
score >= 50Checks if x is not equal to y.
Go
x != y
Checks if age is less than 18.
Go
age < 18Sample Program
This program compares two numbers using all relational operators and prints the results.
Go
package main import "fmt" func main() { a := 10 b := 20 fmt.Println("a == b:", a == b) // false fmt.Println("a != b:", a != b) // true fmt.Println("a > b:", a > b) // false fmt.Println("a < b:", a < b) // true fmt.Println("a >= 10:", a >= 10) // true fmt.Println("b <= 20:", b <= 20) // true }
OutputSuccess
Important Notes
Remember that relational operators return true or false, which you can use in conditions.
Don't confuse assignment (=) with equality (==) in Go.
Relational operators work with numbers, strings, and other comparable types.
Summary
Relational operators compare two values and return true or false.
They are useful to control decisions in your program.
Common operators include ==, !=, >, <, >=, and <=.