Categories: Softwares

Go Course: Flow Control – DEV Community

[ad_1]

Let’s talk about flow control, starting with if/else.

If/Else

This works pretty much the same as you expect but the expression doesn’t need to be surrounded by parentheses ().

func main() 
    x := 10

    if x > 5 
        fmt.Println("x is gt 5")
     else if x > 10 
        fmt.Println("x is gt 10")
     else 
        fmt.Println("else case")
    

Enter fullscreen mode

Exit fullscreen mode

$ go run main.go
x is gt 5
Enter fullscreen mode

Exit fullscreen mode

Compact if

We can also compact our if statements.

func main() 
    if x := 10; x > 5 
        fmt.Println("x is gt 5")
    

Enter fullscreen mode

Exit fullscreen mode

Note: This pattern is quite common

Switch

Next, we have switch statement, which is often a shorter way to write conditional logic.

In Go, the switch case only runs the first case whose value is equal to the condition expression and not all the cases that follow. Hence, unlike other languages, break statement is automatically added at the end of each case.

This means that it evaluates cases from top to bottom, stopping when a case succeeds.
Let’s take a look at an example:

func main() 
    day := "monday"

    switch day 
    case "monday":
        fmt.Println("time to work!")
    case "friday":
        fmt.Println("let's party")
    default:
        fmt.Println("browse memes")
    

Enter fullscreen mode

Exit fullscreen mode

$ go run main.go
time to work!
Enter fullscreen mode

Exit fullscreen mode

Switch also supports shorthand declaration like this.

    switch day := "monday"; day 
    case "monday":
        fmt.Println("time to work!")
    case "friday":
        fmt.Println("let's party")
    default:
        fmt.Println("browse memes")
    
Enter fullscreen mode

Exit fullscreen mode

We can also use the fallthrough keyword to transfer control to the next case even though the current case might have matched.

    switch day := "monday"; day 
    case "monday":
        fmt.Println("time to work!")
        fallthrough
    case "friday":
        fmt.Println("let's party")
    default:
        fmt.Println("browse memes")
    
Enter fullscreen mode

Exit fullscreen mode

And if we run this, we’ll see that after the first case matches the switch statement continues to the next case because of the fallthrough keyword.

$ go run main.go
time to work!
let's party
Enter fullscreen mode

Exit fullscreen mode

We can also use it without any condition, which is the same as switch true.

x := 10

switch 
    case x > 5:
        fmt.Println("x is greater")
    default:
        fmt.Println("x is not greater")

Enter fullscreen mode

Exit fullscreen mode

Loops

Now, let’s turn our attention toward loops.

So in Go, we only have one type of loop which is the for loop.

But it’s incredibly versatile. Same as if statement, for loop, doesn’t need any parenthesis () unlike other languages.

For loop

Let’s start with the basic for loop.

func main() 
    for i := 0; i < 10; i++ 
        fmt.Println(i)
    

Enter fullscreen mode

Exit fullscreen mode

The basic for loop has three components separated by semicolons:

  • init statement: which is executed before the first iteration.
  • condition expression: which is evaluated before every iteration.
  • post statement: which is executed at the end of every iteration.

Break and continue

As expected, Go also supports both break and continue statements for loop control. Let’s try a quick example:

func main() 
    for i := 0; i < 10; i++ 
        if i < 2 
            continue
        

        fmt.Println(i)

        if i > 5 
            break
    
    

    fmt.Println("We broke out!")

Enter fullscreen mode

Exit fullscreen mode

So, the continue statement is used when we want to skip the remaining portion of the loop, and break statement is used when we want to break out of the loop.

Also, Init and post statements are optional, hence we can make our for loop behave like a while loop as well.

func main() 
    i := 0

    for ;i < 10; 
        i += 1
    

Enter fullscreen mode

Exit fullscreen mode

Note: we can also remove the additional semi-colons to make it a little cleaner

Forever loop

Lastly, If we omit the loop condition, it loops forever, so an infinite loop can be compactly expressed. This is also known as the forever loop.

func main() 
    for 
        // do stuff here
    

Enter fullscreen mode

Exit fullscreen mode


This article is part of my open source Go Course available on Github.

Master the fundamentals and advanced features of the Go programming language

Hey, welcome to the course, and thanks for learning Go. I hope this course provides a great learning experience.

This course is also available on my website as well as on Educative.io

Go (also known as Golang) is a programming language developed at Google in 2007 and open-sourced in 2009.

It focuses on simplicity, reliability, and efficiency. It was designed to combine the efficacy, speed, and safety of a statically typed and compiled language with the ease of programming of a dynamic language to…

Christine Carter

Recent Posts

How To Choose the Right Sales Automation Solution

In the relentless pace of today's business landscape, where time is money and efficiency is… Read More

2 days ago

Benefits of Group Dog Training: Why Socializing Your Pup Matters

When it comes to raising a well-rounded and well-behaved canine companion, socialization plays a crucial… Read More

3 days ago

All Characters Who Trained Luke Skywalker

Luke Skywalker, the legendary Jedi Knight who ignited a new hope in the galaxy, didn't… Read More

3 days ago

Top 8 Tips to Find the Best Dental Clinic in Dubai [2024]

When it comes to your dental health, choosing the right clinic is crucial for receiving… Read More

2 weeks ago

Essentials for Effective Multifamily Marketing

In the dynamic world of real estate, multifamily properties present unique marketing challenges and opportunities.… Read More

3 weeks ago

How Couples Salsa Classes Can Strengthen Your Relationship

In the bustling world we inhabit, finding meaningful ways to connect with our partners can… Read More

3 weeks ago