Operators and Expressions
Use arithmetic, comparison, and logical operators in Go programs.
Learning objective: Perform calculations and create true-or-false expressions.
Arithmetic Operators
Go supports common arithmetic operators such as +, -, *, /, and %.
Comparison Operators
Comparison operators compare values and return true or false. Common examples include ==, !=, >, <, >=, and <=.
Logical Operators
Logical operators combine Boolean expressions. Use && for AND, || for OR, and ! for NOT.
Example Code
Create or update your Go file, then run the program using go run main.go.
package main
import "fmt"
func main() {
a := 10
b := 3
fmt.Println("Addition:", a+b)
fmt.Println("Remainder:", a%b)
fmt.Println("Is a greater than b?", a > b)
fmt.Println("Both conditions true?", a > 5 && b < 5)
}
Key points to remember
- The % operator returns the remainder.
- Comparison operators return Boolean values.
- Use parentheses to make complex expressions clearer.
Practice Exercises
- Calculate the total price of two products.
- Check whether a number is greater than 100.
- Use && to combine two conditions.
Continue Learning
After this lesson, continue to the next lesson or explore related tutorials on VisualStudioTutor.com.