Skip to main content

Welcome to a Grasp lesson

Create a free account to keep studying and create your own study path.

Lesson 4

Conditional Statements: If/Else and Switch

Recommended resources

Welcome to the next lesson in our journey to master Go. In our previous session, we covered the fundamental ways Go represents data: using basic types like int, string, and bool, and defining immutable values with constants. You now have the tools to declare and store information.

Today, we'll learn how to make our programs act on that information. A program that only executes a linear sequence of steps is very limited. The real power comes from making decisions and changing behavior based on conditions. This lesson focuses on exactly that: controlling the flow of your program using if/else and switch statements. For a backend developer, this is the bread and butter of implementing business logic, validating requests, and handling different states in your application.

1. Simple Branching with if/else

The most fundamental control structure in programming is the if statement. It allows you to execute a block of code only when a certain condition is true. If it's false, the block is skipped. You can optionally add an else block to provide an alternative path of execution.

Since you have experience with Python, the concept will be familiar, but Go's syntax has some important distinctions.

This diagram shows the basic components of a Go `if` statement: the keyword, the condition that evaluates to true or false, and the code block that runs if the condition is true.

Let's dive into the specifics using "Go by Example," which will be a core resource throughout this course as you requested.

Go by Example: If/Else

This page provides a concise overview of if/else in Go. Please read the entire page, but pay close attention to the first few examples.

Focus on these key points: The basic if/else structure for checking a condition. An if statement can stand alone. How to combine conditions using logical operators && (and) and || (or).

From this reading, let's summarize the key syntactic rules that differ from Python:

  • No Parentheses: Go does not require parentheses () around the condition. This is a stylistic choice to keep the code cleaner.
  • Mandatory Braces: The curly braces {} to define the code block are always required, even for single-line statements. This avoids ambiguity and is a hallmark of Go's design philosophy.
  • else if: The keyword for subsequent checks is else if, not elif as in Python.

For a more conversational walkthrough, the following video explains these concepts with a practical rollercoaster access example.

Golang Tutorial #9 - If, Else If, Else

The presenter in this video from Tech With Tim provides a clear, step-by-step explanation of how to build conditional logic from a simple if to a more complex if-else if-else chain.

Watch the introduction to the basic if statement. Next, see how else provides an alternative path. Finally, understand how to chain multiple conditions with else if.

The if Statement with a Short Statement

Go includes a powerful and idiomatic feature that you won't find in Python. You can include a short initialization statement within the if condition itself. This is most commonly used to declare a variable that is only needed for the purpose of the conditional check.

The syntax looks like this: if initialization_statement; condition { ... }

The key benefit here is scoping. The variable declared in the initialization statement is only visible within the if, else if, and else blocks. This prevents a temporary variable from "leaking" into the surrounding function's scope, making the code cleaner and safer.

Let's look at the example from "Go by Example" again.

Go by Example: If/Else

Revisit the same article to focus on this specific feature.

Read the section that begins with this example. Notice how the num variable is declared and checked in the same line.

In the example if num := 9; num < 0, the variable num is created and assigned the value 9. Then, the condition num < 0 is evaluated. The num variable is accessible in the if, else if, and else blocks, but not outside of them. This is a very common pattern in Go, especially for functions that return a value and an error (which we'll see later).

Finally, it's worth noting that Go does not have a ternary operator. In Python, you might write result = "even" if x % 2 == 0 else "odd". In Go, you must use a full if/else block to achieve the same result.


2. Multi-Way Branching with switch

When you find yourself writing a long if-else if-else if-... chain to check a single variable against many possible values, it can become clumsy. Go provides the switch statement as a cleaner and often more efficient way to handle this.

A switch statement compares an expression against a series of case values. When a match is found, the code block for that case is executed.

Let's turn to "Go by Example" for the syntax.

Go by Example: Switch

This page introduces the switch statement and its various forms.

Start by reading the first two examples: The basic switch, which shows how to check a variable against several cases. The next example, which demonstrates using commas for multiple expressions in one case and the default keyword.

There are two critical features of Go's switch statement that you should internalize:

  1. Implicit break: Unlike C, Java, or JavaScript, Go's switch cases do not "fall through" by default. Once a case is matched and its code is executed, the switch statement terminates. You don't need to add a break at the end of every case. If you want the fallthrough behavior, you must explicitly use the fallthrough keyword.
  2. Flexible Cases: The cases in a switch don't have to be simple constants. They can be expressions, and you can group multiple expressions in a single case using commas.

Advanced switch Forms

The switch statement in Go is more versatile than in many other languages.

switch without an Expression

You can use a switch without providing an expression next to the keyword. In this form, it acts as a cleaner alternative to an if-else if-else chain. The cases themselves become boolean conditions, and the first one that evaluates to true is executed.

Go by Example: Switch

Now, look at the third example on the same page.

Read the example showing a switch with no expression. This is a very idiomatic way to write complex conditional logic in Go.

Type switch

Go also supports a special kind of switch called a "type switch," which lets you determine the specific type of a variable. This is used with a feature called interfaces, which we will cover in detail in a future module. For now, it's enough to recognize the syntax switch v := i.(type). This statement checks the concrete type held by the interface i and allows you to run code specific to that type.

We will not practice this today, but it's important to know it exists as it's a key part of the switch statement's capabilities.


3. Practice Exercise

Let's write some code to solidify these concepts. Imagine you are writing a piece of logic for a backend service that determines a user's permission level based on their role.

Create a new file named conditionals.go and implement the following function.

package main

import "fmt"

// getUserAccessLevel determines the access level string based on a user's role.
// Roles: "admin", "manager", "editor", "viewer".
// Any other role is considered "guest".
func getUserAccessLevel(role string) string {
	var accessLevel string

	// TODO: Use a switch statement to check the user's role.
	// - "admin": "Full Administrative Access"
	// - "manager", "editor": "Content Management Access"
	// - "viewer": "Read-Only Access"
	// - For any other role, assign "Guest Access".
	// Hint: You can group "manager" and "editor" in the same case.
	
	switch role {
	case "admin":
		accessLevel = "Full Administrative Access"
	case "manager", "editor":
		accessLevel = "Content Management Access"
	case "viewer":
		accessLevel = "Read-Only Access"
	default:
		accessLevel = "Guest Access"
	}
	
	return accessLevel
}

func main() {
	// Test the switch statement
	role := "editor"
	fmt.Printf("Role: %s, Access Level: %s\n", role, getUserAccessLevel(role))

	role = "guest_user"
	fmt.Printf("Role: %s, Access Level: %s\n", role, getUserAccessLevel(role))

	// --- Part 2: if/else with a short statement ---

	// TODO: Use an if statement with a short statement to check a score.
	// 1. In one line, declare a variable `score` with the value 85.
	// 2. The condition should check if score >= 60.
	// 3. If it is, print "Access Granted: Score is [score]".
	// 4. Otherwise, print "Access Denied: Score is [score]".
	if score := 85; score >= 60 {
		fmt.Printf("Access Granted: Score is %d\n", score)
	} else {
		fmt.Printf("Access Denied: Score is %d\n", score)
	}

	// Try to print the 'score' variable here. What happens?
	// fmt.Println(score) // This line will cause a compile error: undefined: score
}

Complete the TODO sections in the code. Run the program to verify your logic. Pay special attention to the final commented-out line. Try uncommenting it and running the code again. The compiler error you receive demonstrates the concept of block scope for variables declared in an if statement.


Conclusion

You've now learned how to control the execution path of your Go programs. This is a fundamental skill that moves you from simply listing instructions to creating dynamic, responsive applications.

Key Takeaways:

  • if/else: The standard tool for conditional logic. In Go, remember: no parentheses around conditions, but braces are mandatory.
  • if with short statement: if num := getValue(); num > 10 is a powerful, idiomatic pattern for declaring variables scoped to the conditional block.
  • switch: A cleaner alternative to long if-else if chains. Go's switch features implicit breaks, making it safer and more readable.
  • Expression-less switch: An elegant way to structure complex if/else logic.

With the ability to store data and now make decisions, the next logical step is to perform actions repeatedly. In our next lesson, we will explore loops using Go's versatile for keyword, which will unlock a new level of computational power.