Golang If Else (Syntax, Multiple Conditions, One-Line & Best Practices)

Golang If Else (Syntax, Multiple Conditions, One-Line & Best Practices)

Golang If Else (Quick Cheat Sheet)

If, Else If, Else Syntax

go
if condition1 {
    // executes if condition1 is true
} else if condition2 {
    // executes if condition1 is false and condition2 is true
} else {
    // executes if all above conditions are false
}

Example:

go
age := 17

if age > 18 {
    fmt.Println("Allowed to drive")
} else if age == 17 {
    fmt.Println("Prepare for license")
} else {
    fmt.Println("Not allowed")
}

Key Points

  • Conditions must return a boolean (true or false)
  • Curly braces {} are mandatory in Go
  • else must be on the same line as closing brace

Logical Operators (AND, OR, NOT)

OperatorMeaningExample
&&AND (both must be true)a > 10 && b < 20
||OR (at least one true)`a > 10
!NOT (reverse condition)!(a > 10)

Example:

go
isLoggedIn := true
isAdmin := false

if isLoggedIn && isAdmin {
    fmt.Println("Admin access granted")
} else if isLoggedIn || isAdmin {
    fmt.Println("Limited access")
} else {
    fmt.Println("Access denied")
}

Tip

  • Use && for strict conditions
  • Use || when any condition should pass
  • Use ! to invert logic (e.g., "if NOT logged in")

What is If Statement in Golang

Basic If Statement Example

go
package main

import "fmt"

func main() {
    age := 20

    if age > 18 {
        fmt.Println("You are eligible to vote")
    }
}

Explanation

  • The condition age > 18 is evaluated
  • If true, the code inside {} is executed
  • If false, nothing happens

If Statement with Initialization

Golang allows you to initialize variables inside the if statement itself.

go
package main

import "fmt"

func main() {
    if num := 10; num > 5 {
        fmt.Println("Number is greater than 5")
    }
}

Explanation

  • num := 10 is initialized inside the if
  • The variable is scoped only within the if block
  • Useful for short-lived variables

If Else and Else If in Golang

If Else Example (Beginner)

go
package main

import "fmt"

func main() {
    age := 15

    if age >= 18 {
        fmt.Println("You can vote")
    } else {
        fmt.Println("You cannot vote")
    }
}

Explanation

  • If condition is true → first block runs
  • If condition is false → else block runs

Else If Chain (Multiple Conditions)

Use else if when you need to check multiple conditions in sequence.

go
package main

import "fmt"

func main() {
    marks := 75

    if marks >= 90 {
        fmt.Println("Grade A")
    } else if marks >= 75 {
        fmt.Println("Grade B")
    } else if marks >= 50 {
        fmt.Println("Grade C")
    } else {
        fmt.Println("Fail")
    }
}

Explanation

  • Conditions are checked one by one
  • First matching condition executes
  • Remaining conditions are skipped

Golang If with Multiple Conditions

Using AND (&&) Operator

The AND (&&) operator ensures that all conditions must be true.

go
package main

import "fmt"

func main() {
    age := 25
    hasLicense := true

    if age >= 18 && hasLicense {
        fmt.Println("Allowed to drive")
    }
}

Explanation

  • Both conditions must be true
  • If any condition is false → block will not execute

Using OR (||) Operator

The OR (||) operator allows execution if at least one condition is true.

go
package main

import "fmt"

func main() {
    isAdmin := false
    isModerator := true

    if isAdmin || isModerator {
        fmt.Println("Access granted")
    }
}

Explanation

  • Only one condition needs to be true
  • Useful for permission checks

Combining AND + OR (Real Examples)

You can combine multiple operators to create complex conditions.

go
package main

import "fmt"

func main() {
    age := 20
    hasID := true
    isMember := false

    if (age >= 18 && hasID) || isMember {
        fmt.Println("Access allowed")
    }
}

Explanation

  • (age >= 18 && hasID) must be true OR
  • isMember must be true
  • Parentheses improve readability and avoid confusion

One Line If and Short Conditions

One Line If Example

You can write short if statements in a single line.

go
package main

import "fmt"

func main() {
    num := 10

    if num > 5 { fmt.Println("Number is greater than 5") }
}

Explanation

  • Useful for small conditions
  • Avoid for complex logic (reduces readability)

Inline If with Assignment

Golang allows variable initialization inside an if statement.

go
package main

import "fmt"

func main() {
    if value := 15; value > 10 {
        fmt.Println("Value is greater than 10")
    }
}

Explanation

  • Variable is scoped only within the if block
  • Helps keep code clean and concise

Nested If vs Clean Conditions

Nested If Example

Nested if statements are used when one condition depends on another condition being true.

go
package main

import "fmt"

func main() {
    isLoggedIn := true
    isAdmin := true

    if isLoggedIn {
        if isAdmin {
            fmt.Println("Admin dashboard access granted")
        }
    }
}

Explanation

  • The inner if runs only if the outer condition is true
  • Useful when conditions are dependent

Avoid Deep Nesting

Deep nesting makes code harder to read and maintain. It is better to simplify conditions.

Bad example (deep nesting):

go
if isLoggedIn {
    if isAdmin {
        if hasPermission {
            fmt.Println("Access granted")
        }
    }
}

Better approach:

go
if isLoggedIn && isAdmin && hasPermission {
    fmt.Println("Access granted")
}

Why this is better

  • Easier to read
  • Fewer lines of code
  • Reduces complexity

Real-World Use Cases

Validate User Input (Login Example)

go
email := "user@example.com"
password := "secret123"

if email != "" && password != "" {
    fmt.Println("Valid input")
} else {
    fmt.Println("Missing email or password")
}

Use case

  • Login forms
  • API request validation

Check API Response Status

go
statusCode := 200

if statusCode >= 200 && statusCode < 300 {
    fmt.Println("Request successful")
} else {
    fmt.Println("Request failed")
}

Use case

  • API response handling
  • Error checking in microservices

Feature Flag / Config Checks

go
isFeatureEnabled := true

if isFeatureEnabled {
    fmt.Println("New feature is active")
} else {
    fmt.Println("Using old functionality")
}

Use case

  • Enable/disable features dynamically
  • A/B testing and rollout strategies

Common Mistakes and Fixes

Missing Braces in If Statement

In Golang, curly braces {} are mandatory for if statements.

Incorrect:

go
if x > 10
    fmt.Println("Invalid syntax")

Correct:

go
if x > 10 {
    fmt.Println("Valid syntax")
}

Fix

  • Always use {} even for single-line conditions
  • Go does not support implicit blocks like some other languages

Confusing AND/OR Priority

Mixing && (AND) and || (OR) without parentheses can lead to unexpected results.

go
if a > 10 || b < 20 && c != 0 {
    fmt.Println("Condition met")
}

Problem

  • && has higher priority than ||
  • Expression may not evaluate as expected

Fix

Use parentheses for clarity:

go
if (a > 10 || b < 20) && c != 0 {
    fmt.Println("Condition met")
}

Using Nested If Instead of Clean Logic

Deeply nested if statements reduce readability.

Bad example:

go
if isLoggedIn {
    if isAdmin {
        if hasAccess {
            fmt.Println("Access granted")
        }
    }
}

Better approach:

go
if isLoggedIn && isAdmin && hasAccess {
    fmt.Println("Access granted")
}

Fix

  • Combine conditions where possible
  • Keep logic simple and readable

Frequently Asked Questions

1. How do you write if else in Golang?

In Golang, you use the if, else if, and else keywords with conditions that return boolean values. Curly braces are mandatory and define the code block to execute.

2. Can you write one line if in Golang?

Yes, Golang allows one-line if statements for simple conditions, but they should be avoided for complex logic to maintain readability.

3. How do you use multiple conditions in Golang if?

You can combine conditions using logical operators like && (AND), || (OR), and ! (NOT) to create complex conditional statements.

4. What is the difference between if and else if in Go?

The if statement checks the first condition, while else if allows you to check additional conditions if the first one evaluates to false.

5. Does Golang support ternary operator?

No, Golang does not support the ternary operator. You must use if-else statements instead.

Summary

  • if statements in Golang are used for decision-making
  • Conditions must always return boolean values
  • if, else if, and else help handle multiple outcomes
  • Logical operators (&&, ||, !) allow complex conditions
  • Avoid deep nesting and write clean, readable conditions
  • Use parentheses to avoid confusion in multiple conditions

Official Documentation

Antony Shikubu

Antony Shikubu

Systems Integration Engineer

Highly skilled software developer with expertise in Python, Golang, and AWS cloud services.