Premium Tutorials • Books • Articles • Modern Programming Paths Go Programming Book · Author Bookstore
Lesson 6 of 15

Control Flow: If, Else, and Switch

Make decisions in your Go programs using conditional statements.

Beginner Friendly Runnable Example Go Programming
Learning objective: Use if, else if, else, and switch to control program decisions.

Using if

An if statement runs a block of code only when a condition is true.

Using else

An else block runs when the previous if condition is false.

Using switch

A switch statement is useful when checking one value against several possible cases.

Example Code

Create or update your Go file, then run the program using go run main.go.

package main

import "fmt"

func main() {
    score := 78

    if score >= 80 {
        fmt.Println("Grade A")
    } else if score >= 60 {
        fmt.Println("Grade B")
    } else {
        fmt.Println("Needs improvement")
    }

    day := "Monday"

    switch day {
    case "Monday":
        fmt.Println("Start of the week")
    case "Friday":
        fmt.Println("Almost weekend")
    default:
        fmt.Println("Regular day")
    }
}
Key points to remember
  • Go does not require parentheses around if conditions.
  • The opening brace belongs on the same line as the if or switch statement.
  • A default case is useful when no other case matches.

Practice Exercises

  1. Write an if statement to check whether a person is an adult.
  2. Create a simple grade checker.
  3. Use switch to display a message for different days.

Continue Learning

After this lesson, continue to the next lesson or explore related tutorials on VisualStudioTutor.com.