BudiBadu Logo

Samplebadu

Code with Example
BudiBadu Logo
Samplebadu

Go by Example: If Expressions

Go 1.23

Go's `if` statement is simple yet powerful. It supports an optional initialization statement that runs before the condition, allowing you to declare variables scoped strictly to the `if` block.

Code

package main

import (
    "fmt"
    "math/rand"
    "time"
)

func main() {
    // 1. Basic If-Else
    // Parentheses () around the condition are NOT allowed.
    // Braces {} are REQUIRED.
    x := 10
    if x > 5 {
        fmt.Println("x is greater than 5")
    } else {
        fmt.Println("x is 5 or less")
    }

    // 2. If with Initialization Statement
    // Syntax: if statement; condition { ... }
    // 'n' is initialized, then checked.
    // 'n' is ONLY available inside the if/else blocks.
    if n := getRandomNumber(); n > 50 {
        fmt.Printf("%d is large\n", n)
    } else {
        fmt.Printf("%d is small\n", n)
    }
    
    // fmt.Println(n) // Error: undefined: n

    // 3. Idiomatic Error Handling
    // This pattern is ubiquitous in Go.
    // We try to do something, assign the error to 'err', and check it immediately.
    if err := riskyOperation(); err != nil {
        fmt.Println("Operation failed:", err)
        return // Stop execution
    }
    fmt.Println("Operation succeeded!")
}

func getRandomNumber() int {
    rand.Seed(time.Now().UnixNano())
    return rand.Intn(100)
}

func riskyOperation() error {
    // Simulate an error
    return fmt.Errorf("connection timeout")
}

Explanation

The if statement in Go is similar to other C-like languages but with a few key syntax differences: parentheses (...) around the condition are not needed (and removed by gofmt), but the braces {...} are mandatory, even for one-liners.

A powerful feature of Go's if is the initialization statement. You can execute a simple statement (like a variable declaration) before the condition, separated by a semicolon. The syntax is: if init; condition { ... }.

Variables declared in this initialization step are scoped to the if block and its corresponding else blocks. This is incredibly useful for keeping variables like err or temporary calculation results from polluting the surrounding function scope.

  • Syntax: No parens, mandatory braces.
  • Init Statement: if v := calc(); v > 10 { ... }
  • Scope: Variables from init are local to the if/else chain.
  • Pattern: Extremely common for error handling: if err := fn(); err != nil { ... }

Code Breakdown

14-18
Standard if-else structure. Note the lack of parentheses around 'x > 5'. The opening brace '{' must be on the same line as the 'if' keyword.
24
The initialization statement. 'n := getRandomNumber()' runs first. Then 'n > 50' is evaluated. 'n' is visible inside the 'if' block and the 'else' block, but not after.
35
The classic "check error" pattern. We call 'riskyOperation()', capture the error in 'err', and check if it's not nil, all in one line. This keeps the 'err' variable tightly scoped to the error handling logic.