Introduction to Control Structures in Go

Introduction to Control Structures

Are you ready to dive deeper into Go? In this lesson, we will learn about control structures. Control structures are fundamental building blocks in programming that empower your code to take different actions based on various situations.

What You'll Learn

We'll be focusing on the if and else statements. These are the cornerstones of decision making in Go. To illustrate, suppose you want to travel, but your ability to do so depends on whether you have a passport. In programming terms, we model this real-world scenario as follows:

package main

import "fmt"

func main() {

    hasPassport := true

    if hasPassport {
        fmt.Println("You are eligible to travel.")
    } else {
        fmt.Println("You cannot travel without a passport.")
    }
}

As you can see, the if statement checks whether the condition — in this case, having the passport being true is met. If so, the action within the if block, printing "You are eligible to travel," is executed. Otherwise, the code within the else block, which states "You cannot travel without a passport," is executed.

A Note on Syntax

In addition to understanding the if and else statements, mastering the syntax, particularly the use of braces {} that delineate blocks of code, is crucial. Braces, in combination with the if and else keywords, define the scope and block of instructions attached to each condition in Go.

if passport {
    fmt.Println("You are eligible to travel.")  // This statement belongs to the if condition
    // Any additional code dependent on the passport being true would be placed here
} else {
    fmt.Println("You cannot travel without a passport.")  // This statement belongs to the else condition
    // Code to execute when the passport condition is false would be placed here
}
// Any code here would not be part of the if-else block and executes regardless of the passport condition

After each if or else statement, a block of code is enclosed within braces {} to introduce the instructions that should be executed if the condition is met. This syntax structure ensures your program can clearly follow which instructions belong to which condition, thereby facilitating an organized and error-free decision-making process.

Role of Parentheses in if Statements

Sign up

Join the 1M+ learners on CodeSignal

Be a part of our community of 1M+ users who develop and demonstrate their skills on CodeSignal