Go If-Else Statement

Go If Else Statement is used to conditionally execute either of the two code blocks, based on the result of a condition or boolean expression.

In this tutorial, we will learn the syntax of Go If Else statement, its syntax and usage with examples.

An if statement evaluates a condition that must produce a Boolean value. When the condition is true, Go executes the if block. When it is false, Go executes the optional else block.

Syntax

The syntax of Go If Else statement is

</>
Copy
 if condition {
     //code
 } else {
     //code
 }

where the condition is a boolean expression or would return a boolean value.

If the condition evaluates to true, the code inside if-block executes. If the expression evaluates to false, the code inside the else-block executes.

Parentheses around the condition are not required in Go. The opening brace must appear on the same line as the if or else clause.

Examples

In the following example, we will write an if-else statement with the condition that a is less than b.

example.go

</>
Copy
package main

import "fmt"

func main() {
	var a int = 5
	var b int = 20
 
	if a < b {
		fmt.Println("a is less than b")
	} else {
		fmt.Println("a is not less than b")
	}
}

Since, the value is a is less than that of b, the code in if-block executes.

Output

a is less than b

Now, let us take the values in a and b, such that a is not less than b, and observe the output.

example.go

</>
Copy
package main

import "fmt"

func main() {
	var a int = 36
	var b int = 20

	if a < b {
		fmt.Println("a is less than b")
	} else {
		fmt.Println("a is not less than b")
	}
}

Since, the value is a is not less than that of b, the code in else-block executes.

Output

a is not less than b

Go If Else If

We can extend an if-else statement to check multiple conditions in a ladder and execute the corresponding block of code where the condition becomes true.

The syntax of Go If-Else-If statement is:

</>
Copy
 if condition_1{
     //code
 } else if condition_2 {
     //code
 } else if condition_3 {
     //code
 } else {
     //code
 }

where the condition is a boolean expression or would return a boolean value.

The execution falls from top to bottom, and when a condition evaluates to true, then the corresponding code block executes, and the execution comes out of this if-else-if ladder. If no condition is true, then the else-block code executes.

Example

In the following example, we will write an if-else-if statement.

example.go

</>
Copy
package main  

import "fmt"  

func main() { 
	var a int = 20
	var b int = 20
 
	if(a<b){
		fmt.Println("a is less than b")
	} else if(a==b) {
		fmt.Println("a is equal to b")
	} else {
		fmt.Println("a is greater to b")
	}
}

Output

a is equal to b

Go If-Else with Multiple Conditions

Use the logical AND operator && when all conditions must be true. Use the logical OR operator || when at least one condition must be true.

The following program checks whether a number is within a specified range.

example.go

</>
Copy
package main

import "fmt"

func main() {
	number := 25

	if number >= 10 && number <= 50 {
		fmt.Println("number is between 10 and 50")
	} else {
		fmt.Println("number is outside the range")
	}
}

Output

number is between 10 and 50

Logical expressions can combine comparisons, Boolean variables, and function results. Add parentheses when they make a complex condition easier to read.

Go If Statement with a Short Variable Declaration

Go allows a short statement before the condition. It is commonly used to initialize a value that is needed only inside the if, else if, and else blocks.

</>
Copy
if initialization; condition {
    // code
} else {
    // code
}

In the following example, length is available throughout the complete if-else statement, but it is not available after that statement ends.

example.go

</>
Copy
package main

import "fmt"

func main() {
	name := "Gopher"

	if length := len(name); length > 5 {
		fmt.Println("name has more than five characters")
	} else {
		fmt.Println("name has five or fewer characters")
	}
}

Output

name has more than five characters

Nested If-Else Statements in Go

An if or else block can contain another conditional statement. This is useful when a second decision should be evaluated only after the first condition has been satisfied.

example.go

</>
Copy
package main

import "fmt"

func main() {
	age := 24
	hasID := true

	if age >= 18 {
		if hasID {
			fmt.Println("entry allowed")
		} else {
			fmt.Println("identification required")
		}
	} else {
		fmt.Println("entry not allowed")
	}
}

Output

entry allowed

Deeply nested conditions can become difficult to read. When possible, use early returns, helper functions, or a clearer sequence of conditions.

Go If-Else Shorthand and Conditional Expressions

Go does not provide a ternary conditional operator such as condition ? value1 : value2. Use a regular ifelse statement when a value depends on a condition.

example.go

</>
Copy
package main

import "fmt"

func main() {
	score := 72
	result := "fail"

	if score >= 40 {
		result = "pass"
	}

	fmt.Println(result)
}

Output

pass

Common Go If-Else Mistakes

  • Placing else on a new line: In Go, the closing brace and else must be on the same line because of automatic semicolon insertion.
  • Using = instead of ==: Use == to compare values. The single equals sign is used for assignment.
  • Using a non-Boolean condition: Go does not treat integers or strings as truthy or falsy values. The condition must evaluate to bool.
  • Expecting every condition to run: In an if-else-if ladder, Go stops after the first condition that evaluates to true.
  • Looking for a ternary operator: Go does not include the ?: conditional operator.

Frequently Asked Questions about Go If-Else

How do you write else if in Go?

Write else if after the closing brace of the preceding block. The else keyword must remain on the same line as that closing brace.

Can a Go if statement contain multiple conditions?

Yes. Combine conditions with && for logical AND and || for logical OR. Each combined expression must ultimately evaluate to a Boolean value.

Does Go have an if-else shorthand operator?

Go does not have a ternary operator. It does support a short initialization statement before an if condition, such as if value := getValue(); value > 0.

Can an if condition use an assignment in Go?

You can place an initialization or assignment before the condition by separating it with a semicolon. The condition after the semicolon must still evaluate to bool.

Are parentheses required around Go if conditions?

No. Go normally omits parentheses around an if condition. Parentheses may still be used within a larger Boolean expression to make grouping clear.

Go If-Else Tutorial Editorial QA Checklist

  • Confirm that every Go if condition evaluates to a Boolean value.
  • Verify that each else keyword appears on the same line as the preceding closing brace.
  • Check that comparison examples use == rather than assignment with =.
  • Run the examples to confirm that the displayed if-else outputs match the source code.
  • Confirm that the short-statement example correctly explains the scope of the initialized variable.
  • Ensure the tutorial does not imply that Go supports a ternary conditional operator.

Conclusion

In this Go Tutorial, we learned about Go If-Else statement and Go If-Else-If, their syntax and usage with example programs.