Skip to content

Conditionals

Sample code link: (https://repl.it/@jjoco/go-conditionals)

Traditional If, Else-If, Else Statements

Like all other programming languages, Go has traditional if-else statements; the main difference is the lack of parentheses around the condition:

Syntax

1
2
3
4
5
6
7
if condition {
    //Do stuff in first condition ...
} else if otherCondition {
    //Do stuff in otherCondition...
} else {
    //Do stuff if none of the above is satisfied ...
}

Example

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
count := 6

if count < 10 {
    fmt.Printf("Count is below 10 at value %d\n", count)
}
// Output = "Count is below 10 at value 6"

count = 51
if count %2 == 0 {
    fmt.Printf("Count is even!\n")
} else {
    fmt.Printf("Count is odd!\n")
}
//Output = "Count is odd!"

count = 25
if count %15 == 0 {
    fmt.Printf("FizzBuzz\n")
} else if count % 5 == 0 {
    fmt.Printf("Buzz\n")
} else if count % 3 == 0 {
    fmt.Printf("Fizz\n")
} else {
    fmt.Printf("NoneOfTheAbove\n")
}
//Output = "Buzz"
In the above example, we check to see if a count is divsible by a certain number, and the respective case is executed.

If with Short Assignment

In Go, the user can assign a variable and condition on that variable on the same line (separated by a :), like the following

1
2
3
4
if shortStatementInt := 32; shortStatementInt > 30{
    fmt.Printf("shortStatementInt is above 30!\n")
}
//Output = "shortStatementInt is above 30!"
In the above example, shortStatementInt is assigned, then evaluated in the condition following the :