golang can make choices with data. This data (variables) are used with a condition: if statements start with a condition. A condition may be (x > 3), (y < 4), (weather = rain).

What do you need these conditions for? Only if a condition is true, code is executed.

If statements are present in your everyday life, some examples:

  • if (elevator door is closed), move up or down.
  • if (press tv button), next channel

Download PDF

If statements in golang

Example

The program below is an example of an if statement.

1
2
3
4
5
6
7
8
9
10
11
package main

import "fmt"

func main() {
var x = 3

if ( x > 2 ) {
fmt.Printf("x is greater than 2");
}
}

golang runs the code block only if the condition (x >2) is true. If you change variable x to any number lower than two, its codeblock is not executed.

Else

You can execute a codeblock if a condition is not true

1
2
3
4
5
6
7
8
9
10
11
12
13
package main

import "fmt"

func main() {
var x = 1

if ( x > 2 ) {
fmt.Printf("x is greater than 2");
} else {
fmt.Printf("condition is false (x > 2)");
}
}

Video

Video tutorial below

Exercises

  1. Make a program that divides x by 2 if it’s greater than 0
  2. Find out if if-statements can be used inside if-statements.

Download Answers