Search⌘ K

Important Characteristics of Go: Control

Explore Go's control structures to manage program flow efficiently. Understand how to use if, else, and switch statements without parentheses, handle errors with idiomatic patterns, and simplify complex conditions. This lesson helps you write clear and maintainable Go code for various practical applications.

Controlling program flow

So far, we have seen Go variables, but how do we change the flow of a Go program based on the value of a variable or some other condition? Go supports the if/else and switch control structures. Both control structures can be found in most modern programming languages, so if a developer has already programmed in another programming language, they should already be familiar with if and switch. The if statements use no parenthesis for embedding the conditions that need to be examined because Go does not use parentheses in general. As expected, if has support for else and else if statements.

if statement

To demonstrate the use of if, let's use a very common pattern in Go that is used almost everywhere. This pattern says that if the value of an error variable as returned from a function is nil ...