Important Characteristics of Go: Control
Let’s learn how to control program flow.
We'll cover the following
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
, then everything is OK with the function execution. Otherwise, there is an error condition somewhere that needs special care. This pattern is usually implemented as follows:
Get hands-on with 1400+ tech skills courses.