Topic Overview

Welcome! Today, we're diving into conditional statements in Go, focusing on the if statement, and we'll explore how to utilize the break and continue statements within loops. As you've learned, loops execute code multiple times, but by integrating conditional logic and these control flow statements, we can create more powerful and efficient programs. Let's explore these concepts in Go!

The 'if' Statement

In Go, the if statement allows us to execute actions based on certain conditions. Take a look at this example that determines what message to print based on the temperature value:

We can also evaluate multiple conditions using else if. This means, "If the earlier condition isn't true, then check this one":

The 'break' Statement

The break statement in Go is used to exit a loop early when a specific condition is met:

The 'continue' Statement

The continue statement allows us to skip the rest of the loop code for the current iteration only:

Use-case with a For Loop

By using the tools we've discussed, we can develop more flexible loops. Here's a snippet where we stop the loop once we find "Charlie":

Lesson Summary and Practice

Congratulations! You've now learned about Go's if statement, as well as the break and continue statements and their applications within loops. To solidify your understanding, you are encouraged to complete the following practice exercises: write a program that uses if statements to decide what flavor of ice cream to serve based on a given temperature range, implement a loop that skips printing numbers divisible by a given value using continue, and finally, create a loop that breaks when a condition is met, such as finding a specific word in a list. Happy coding!

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