Go (Golang) / Control Flow and Functions

Mastering Control Flow in Go

This tutorial will guide you through the fundamental aspects of controlling the flow of a Go program using conditional statements and loops. It's designed for beginners and will g…

Tutorial 1 of 5 5 resources in this section

Section overview

5 resources

Explains how to use conditional statements, loops, and functions in Go.

1. Introduction

This tutorial aims to give you a clear understanding of how to control the flow of a Go program. We will be focusing on conditional statements (if, if-else, switch) and loops (for, while). By the end of this tutorial, you will be able to write and understand Go programs that feature complex control flow.

You will learn:

  • How to use conditional statements.
  • How to use loops.
  • The concepts behind controlling the flow of programs.

Prerequisites:

  • Basic understanding of Go programming language.
  • Installed Go environment on your local machine.

2. Step-by-Step Guide

Conditional Statements

In Go, we use conditional statements to make decisions based on certain conditions.

If Statement

The if statement is used to test a condition. If the condition is true, the block of code inside the if statement will be executed.

if condition {
    // code to be executed if condition is true
}

If-Else Statement

The if-else statement is used when you want to perform a different operation in the case where the initial if condition is not met.

if condition {
    // code to be executed if condition is true
} else {
    // code to be executed if condition is false
}

Switch Statement

The switch statement is used to select one of many blocks of code to be executed.

switch condition {
case n:
    // code to be executed if condition = n
default:
    // code to be executed if no case matches
}

Loops

Loops are used when we want to repeat a block of code multiple times.

For Loop

In Go, the for loop is the only loop statement. It can be used in three forms.

  • The simple loop
for condition {
    // code to be executed while condition is true
}
  • The pre and post statement loop
for initialization; condition; post {
    // code to be executed while condition is true
}
  • The infinite loop
for {
    // code to be executed infinitely
}

3. Code Examples

If-Else Statement

package main

import "fmt"

func main() {
    age := 18

    if age >= 18 {
        fmt.Println("You are eligible to vote.")
    } else {
        fmt.Println("You are not eligible to vote.")
    }
}

This code will output "You are eligible to vote." since the age variable is 18, which is greater than or equal to 18.

Switch Statement

package main

import "fmt"

func main() {
    day := "Friday"

    switch day {
    case "Monday":
        fmt.Println("Today is Monday.")
    case "Tuesday":
        fmt.Println("Today is Tuesday.")
    case "Friday":
        fmt.Println("Today is Friday.")
    default:
        fmt.Println("Invalid day.")
    }
}

This code will output "Today is Friday." since the day variable matches the "Friday" case.

For Loop

package main

import "fmt"

func main() {
    for i := 0; i < 5; i++ {
        fmt.Println(i)
    }
}

This code will output the numbers from 0 to 4 in the console.

4. Summary

We have covered how to use conditional statements and loops in Go. You should now feel confident in controlling the flow of a Go program. For further learning, you could try implementing nested if-else statements and nested loops.

5. Practice Exercises

  1. Create a Go program that prints out the numbers from 1 to 10 using a for loop.
  2. Create a Go program that checks if a number is even or odd using an if-else statement.
  3. Create a Go program that prints out the days of the week using a switch statement.

Take your time to work on these exercises. They will help solidify your understanding of control flow in Go. Happy coding!

Need Help Implementing This?

We build custom systems, plugins, and scalable infrastructure.

Discuss Your Project

Related topics

Keep learning with adjacent tracks.

View category

HTML

Learn the fundamental building blocks of the web using HTML.

Explore

CSS

Master CSS to style and format web pages effectively.

Explore

JavaScript

Learn JavaScript to add interactivity and dynamic behavior to web pages.

Explore

Python

Explore Python for web development, data analysis, and automation.

Explore

SQL

Learn SQL to manage and query relational databases.

Explore

PHP

Master PHP to build dynamic and secure web applications.

Explore

Popular tools

Helpful utilities for quick tasks.

Browse tools

CSS Minifier & Formatter

Clean and compress CSS files.

Use tool

Lorem Ipsum Generator

Generate placeholder text for web design and mockups.

Use tool

HTML Minifier & Formatter

Minify or beautify HTML code.

Use tool

Keyword Density Checker

Analyze keyword density for SEO optimization.

Use tool

JSON Formatter & Validator

Beautify, minify, and validate JSON data.

Use tool

Latest articles

Fresh insights from the CodiWiki team.

Visit blog

AI in Drug Discovery: Accelerating Medical Breakthroughs

In the rapidly evolving landscape of healthcare and pharmaceuticals, Artificial Intelligence (AI) in drug dis…

Read article

AI in Retail: Personalized Shopping and Inventory Management

In the rapidly evolving retail landscape, the integration of Artificial Intelligence (AI) is revolutionizing …

Read article

AI in Public Safety: Predictive Policing and Crime Prevention

In the realm of public safety, the integration of Artificial Intelligence (AI) stands as a beacon of innovati…

Read article

AI in Mental Health: Assisting with Therapy and Diagnostics

In the realm of mental health, the integration of Artificial Intelligence (AI) stands as a beacon of hope and…

Read article

AI in Legal Compliance: Ensuring Regulatory Adherence

In an era where technology continually reshapes the boundaries of industries, Artificial Intelligence (AI) in…

Read article

Need help implementing this?

Get senior engineering support to ship it cleanly and on time.

Get Implementation Help