Go Operators and Conditions
Operators work with values, and conditions decide which code runs.
Arithmetic Operators
| Operator | Name | Example | Result |
|---|---|---|---|
+ | Add | 11 + 4 | 15 |
- | Subtract | 11 - 4 | 7 |
* | Multiply | 11 * 4 | 44 |
/ | Divide | 11 / 4 | 2 |
% | Remainder | 11 % 4 | 3 |
Example
package main
import "fmt"
func main() {
fmt.Println(11 / 4)
fmt.Println(11.0 / 4)
fmt.Println(11 % 4)
balance := 800
balance += 200
balance -= 150
balance++
fmt.Println(balance)
}2 2.75 3 851
Dividing two whole numbers gives a whole number. In Go, x++ is a statement on its own line; you cannot write y := x++.
Comparison and Logical Operators
Comparison operators return true or false: ==, !=, >, <, >=, <=.
Logical operators combine conditions:
&&(and): both must be true||(or): at least one must be true!(not): reverses the value
if and else
Go does not use brackets around the condition, but the curly braces are always required.
Example
package main
import "fmt"
func main() {
marks := 67
if marks >= 80 {
fmt.Println("Grade A")
} else if marks >= 60 {
fmt.Println("Grade B")
} else {
fmt.Println("Grade C")
}
age := 22
hasCard := false
if age >= 18 && !hasCard {
fmt.Println("Please apply for your ID card")
}
}Grade B Please apply for your ID card
The else must be on the same line as the closing } of the if. Putting it on a new line is a compile error in Go.
if with a Short Statement
You can run a short statement before the condition. The variable created there exists only inside the if and else blocks.
Example
package main
import "fmt"
func main() {
price := 1200
if total := price * 3; total > 3000 {
fmt.Println("Free delivery on Rs", total)
} else {
fmt.Println("Delivery charge applies on Rs", total)
}
}Free delivery on Rs 3600
switch
switch checks a value against several cases. Go runs only the matching case, so you do not need break.
Example
package main
import "fmt"
func main() {
day := "Friday"
switch day {
case "Saturday", "Sunday":
fmt.Println("Weekend")
case "Friday":
fmt.Println("Short day, Jummah prayers")
default:
fmt.Println("Normal working day")
}
temp := 36
switch {
case temp > 40:
fmt.Println("Extreme heat")
case temp > 30:
fmt.Println("Hot")
default:
fmt.Println("Pleasant")
}
}Short day, Jummah prayers Hot
| switch feature | Example |
|---|---|
| Several values in one case | case "Saturday", "Sunday": |
| Default case | default: |
| No value after switch | Works like an if / else if chain |
fallthrough | Continues into the next case (rarely used) |
Exercise
Exercise
What does fmt.Println(17 / 5) print in Go?
