Golang If, Else Statements

These Go examples use if, else if and else statements to test values. They explore correct syntax and performance.

If-statement. An if tests a variable in some way.

In Go we can build complex if constructs with else-if and else parts. Statements are evaluated until a condition is true.

 

 

With initialization statements, we can declare variables in the same line as an if-statement. This syntax leads to clean, understandable code.

 

 

An example. We see an if-statement with else-if and else parts. The variable named "value" is initialized to 5. The first if-statement test, >= 5, evaluates to true.

 

Note: The condition of an if-statement has no surrounding parentheses. The body statements are surrounded by curly braces.

Note 2: In Go the starting curly brace must be placed at the end of the same line. The Gofmt command can help with formatting issues.

Based on:

Golang 1.4

Golang program that uses if, else statements

package main

import "fmt"

func main() {
    value := 10

    // Test the value with an if-else construct.
    if value >= 5 {
	fmt.Println(5)
    } else if value >= 15 {
	fmt.Println(15) // Not reached.
    } else {
	fmt.Println("?") // Not reached.
    }
}

Output

5

Initialization statements. A variable can be declared and initialized before the condition of an if-statement (on the same line). This syntax makes sense.

Scope: The variable is scoped to the if-statement and its contents. Here we cannot reference "t" outside the if.

Golang program that uses if with initialization statement

package main

import "fmt"

func test() int {
    return 100
}

func main() {
    // Initialize a variable in an if-statement.
    // ... Then check it against a constant.
    if t := test(); t == 100 {
	fmt.Println(t)
    }
}

Output

100

Initialization scope. When we declare a variable at the start of an if-statement, it is scoped to that if-statement (and any else-if and elses).

Undefined: If we use the variable outside its scope, an "undefined" error will occur. This is a compile-time error.

Golang program that uses causes error, undefined variable

package main

import "fmt"

func main() {
    mult := 10

    // The variable "t" can be accessed only in the if-statement.
    if t := 100 * mult; t >= 200 {
	fmt.Println(t)
    }
    // This causes an error.
    fmt.Println(t)
}

Output

C:\programs\file.go:16: undefined: t

A summary. Ifs are powerful in Go. In most ways they are the same as those in C-like languages. But the initialization statement feature provides a new, scoped variable for the block.