Learning Golang: if and else

Share on:

This is part 19 of my journey learning Golang.

Conditionals

Any program can be written in terms of three control structures:

  • the sequence structure, in which expressions are executed in sequence, one after the other, in the order that they are written;
  • the selection structure, in which a statement can be executed or not, depending on some condition; and
  • the iteration structure, in which statements may be executed repeatedly until a condition becomes true (or false).

Conditionals are selection structures. The provide a way for expressing decision-making in a program. Depending on the value of an expression, the program may execute (or not) one or more statements.

Go provides two keywords for implementing conditionals: if and switch. This article focuses on the if construct.

if

The if keyword starts a selection statement. It evaluates the boolean expression that immediately follows it. If the value of the expression is true, a block of statements is executed. If the value is false, the block os statements is not executed. The block can contain zero, one or several statements.

For example:

 1package main
 2
 3import (
 4  "fmt"
 5  "math/rand"
 6  "time"
 7)
 8
 9func main() {
10  // Initialize random number generator.
11  r := rand.New(rand.NewSource(time.Now().UnixNano()))
12
13  // Generate 2 small integer numbers.
14  mine := r.Intn(10)
15  yours := r.Intn(10)
16
17  // Print out the random numbers.
18  fmt.Println("Mine:", mine)
19  fmt.Println("Yours:", yours)
20
21  // Print out whether I won.
22  if mine > yours {
23    fmt.Println("I win.")
24  }
25}

Source: learning-go/conditionals/if.go

When run repeatedly, the program produces an output like this:

 1❯ bin/go run conditionals/if.go
 2Mine: 5
 3Yours: 5
 4
 5❯ bin/go run conditionals/if.go
 6Mine: 5
 7Yours: 0
 8I win.
 9
10❯ bin/go run conditionals/if.go
11Mine: 2
12Yours: 7

Notice than when the value of “mine” is greater than the value of “yours”, it prints out “I win.” In the other cases (if it is the same or smaller) it doesn’t print any additional message.

Keep in mind that the block of code following the if can have as many statements as you need, not just one as in the example. It can also have no statements – but in this case it will be rather pointless.

Comparison operators

Go’s comparison operators (also called “relational” operators) are particularly useful for conditional expressions. For example:

Operator Meaning
== Equal to
!= Different from
> Greather than
< Less than
>= Greather than or equal to
<= Less than or equal to

These operators compare two arguments (to their left and to their right) and produce a boolean result, i.e. true or false depending on whether the condition is true or not.

else

The else keyword, in an if statement, executes a block of code if and only if the expression of the if statement was false.

For example:

 1package main
 2
 3import (
 4  "fmt"
 5  "math/rand"
 6  "time"
 7)
 8
 9func main() {
10  // Initialize random number generator.
11  r := rand.New(rand.NewSource(time.Now().UnixNano()))
12
13  // Generate 2 integer numbers.
14  limit := r.Intn(10)
15  value := r.Intn(20)
16
17  // Print out the random numbers.
18  fmt.Println("Limit:", limit)
19  fmt.Println("Value:", value)
20
21  // Print out result of comparison.
22  if value > limit {
23    fmt.Println("Above limit.")
24  } else {
25    fmt.Println("Within limit.")
26  }
27}

Source: learning-go/conditionals/if-else.go

When executed repeatedly, the program will produce output like this:

 1❯ bin/go run conditionals/if-else.go
 2Limit: 4
 3Value: 4
 4Within limit.
 5
 6❯ bin/go run conditionals/if-else.go
 7Limit: 9
 8Value: 7
 9Within limit.
10
11❯ bin/go run conditionals/if-else.go
12Limit: 6
13Value: 19
14Above limit.

Notice that when the value is greater than the limit, it prints out “Above limit.” and when the value is less than or equal to the limit, it prints out “Within limit.”

Keep in mind that the blocks of code following the if and else keywords can have as many statements as you need, not just one as in the example.

else if

The else keyword can be followed by another if statement. The block of the new if statement will be executed if the expression of the previous if statement was false, and the expression is the new if statement is true.

For example:

 1package main
 2
 3import (
 4  "fmt"
 5  "math/rand"
 6  "time"
 7)
 8
 9func main() {
10  // Initialize random number generator.
11  r := rand.New(rand.NewSource(time.Now().UnixNano()))
12
13  // Generate 2 integer numbers.
14  limit := r.Intn(10)
15  value := r.Intn(20)
16
17  // Print out the random numbers.
18  fmt.Println("Limit:", limit)
19  fmt.Println("Value:", value)
20
21  // Print out result of comparison.
22  if value > limit {
23    fmt.Println("Above limit.")
24  } else if value < limit {
25    fmt.Println("Under limit.")
26  } else {
27    fmt.Println("At the limit.")
28  }
29}
30

Source: learning-go/conditionals/if-else-if.go

Produces an output like this:

 1❯ bin/go run conditionals/if-else-if.go
 2Limit: 1
 3Value: 1
 4At the limit.
 5
 6❯ bin/go run conditionals/if-else-if.go
 7Limit: 8
 8Value: 14
 9Above limit.
10
11❯ bin/go run conditionals/if-else-if.go
12Limit: 4
13Value: 2
14Under limit.

Notice that when the value is greater than the limit, the block for the first if statement is executed; when the value is less than the limit, the block for the second if statement is executed; and when neither of these conditions is true, i.e. when both the value and the limit are the same, the block for the final else statement is executed.

Keep in mind that you can chain as many else if statements as necessary, each with a different condition the must be true for its block to be executed. The sequence may or may not have a final else clause not followed by a new if statement.

else if chains

else if statements can be chained as many times as necessary. The block for the first condition that evaluates to true will be executed, and the others will be skipped. If no condition is true, and there is an else clause, its block will be executed. If there isn’t an else clause, then no block will be executed for that chain.

For example:

 1package main
 2
 3import (
 4  "os"
 5  "bufio"
 6  "fmt"
 7  "strings"
 8)
 9
10func main() {
11  // Ask the user to enter a number.
12  reader := bufio.NewReader(os.Stdin)
13  fmt.Print("What position did you finish at? ")
14  positionInput, _ := reader.ReadString('\n')
15  position := strings.TrimSuffix(positionInput, "\n")
16
17  // Print out message for the position.
18  if position == "1" {
19    fmt.Println("Congrats! You finished in first place.")
20  } else if position == "2" {
21    fmt.Println("You were a close second.")
22  } else if position == "3" {
23    fmt.Println("You finished in third.")
24  } else {
25    fmt.Println("Better luck next time!")
26  }
27}

Source: learning-go/conditionals/if-else-chain.go

The program above produces this output:

 1❯ bin/go run ./conditionals/if-else-chain.go
 2What position did you finish at? 1
 3Congrats! You finished in first place.
 4
 5❯ bin/go run ./conditionals/if-else-chain.go
 6What position did you finish at? 2
 7You were a close second.
 8
 9❯ bin/go run ./conditionals/if-else-chain.go
10What position did you finish at? 3
11You finished in third.
12
13❯ bin/go run ./conditionals/if-else-chain.go
14What position did you finish at? 4
15Better luck next time!

Takeaways

  • Go provides the if keyword for creating a selection strucuture that will only execute a block of statements if a condition is true.
  • The optional else clause will execute a block of statements if the previous condition was not true.
  • An else clause can start a new if statement. That else clause (and its if statement) will only execute if the condition of the preceding if statement was false.
  • Only one block of a sequence of if, else if and else keywords will be executed.
  • If no if condition was true, and no else clause was provided, no statement will be executed.
  • The program flow will continue on the next statement following the end of the entire sequence of if, else if and else blocks.
  • the conditions following the if can be as complex as necessary. for instance they can use Go’s logical operators (&&, ||, !) to combine multiple boolean values.

comments powered by Disqus