If/Else & Switch

Duration: 10 min•Difficulty: Easy•

Conditional statements are used to make decisions in code.

Concept

The computer will check if a condition is true. If yes, run Code A. If no, run Code B (else).

When to use?

  • Validating user input (e.g., age > 17).
  • Business logic (e.g., if balance is enough, process transaction).
MAIN.GO
package main
import "fmt"
func main() {
num := 7
if num%2 == 0 {
fmt.Println(num, "is Even")
} else {
fmt.Println(num, "is Odd")
}
}

switch is a cleaner form of nested if-else chains.

When to use?

Use switch if you are comparing a single variable against many specific values. Examples: Checking days (Monday, Tuesday...), Checking order status (Pending, Paid, Shipped).

MAIN.GO
package main
import "fmt"
func main() {
i := 2
fmt.Print("Number ", i, " is ")
switch i {
case 1:
fmt.Println("One")
case 2:
fmt.Println("Two")
case 3:
fmt.Println("Three")
default:
fmt.Println("Others")
}
}