Go - If Else Example

1. Introduction

The if/else construct is a fundamental part of programming logic, allowing for conditional execution of code blocks. In Go, the if/else statement operates similarly to other C-like languages, with some idiomatic differences. This blog post will provide an example of how to use if/else in Go, including the use of initialization statements.

Definition

In Go, an if statement is used to test a condition and execute a block of code if the condition is true. If it's false, the program can execute an alternative block of code using an else or else if clause. The condition does not need to be surrounded by parentheses, unlike in many other languages, but the braces {} are required.

2. Program Steps

1. Use a simple if statement to check a condition.

2. Use an else statement to provide an alternative execution path.

3. Include an else if for multiple conditions.

4. Utilize an if statement with an initialization statement.

3. Code Program

package main

import "fmt"

func main() {
	// Step 1: Check if a number is positive
	number := 42
	if number > 0 {
		fmt.Println(number, "is positive")
	}

	// Step 2 & 3: Use else if to check additional conditions
	if number%2 == 0 {
		fmt.Println(number, "is even")
	} else if number%2 != 0 {
		fmt.Println(number, "is odd")
	}

	// Step 4: If statement with initialization
	if squared := number * number; squared > 1000 {
		fmt.Println(number, "squared is greater than 1000")
	} else {
		fmt.Println(number, "squared is not greater than 1000")
	}
}

Output:

42 is positive
42 is even
42 squared is greater than 1000

Explanation:

1. package main - The package declaration for the Go program.

2. import "fmt" - Imports the Format package for formatted I/O.

3. number := 42 - Declares and initializes number with 42.

4. The first if statement checks if number is greater than 0 and prints that it is positive.

5. An else if statement checks if number is even by checking the remainder of division by 2.

6. Another else if could check for other conditions - in this case, it's redundant because the only other option is odd, but it demonstrates the syntax.

7. The if with initialization if squared := number * number; initializes squared and checks if it's greater than 1000 in the same statement.

8. Each fmt.Println prints the result of the condition checks to the console.

9. The output confirms that 42 is positive, even, and its square is greater than 1000.


Comments