Go > Core Go Basics > Control Flow > If statements

Simple 'if' statement in Go

This snippet demonstrates a basic 'if' statement in Go, showing how to execute code conditionally based on a boolean expression.

Basic 'if' statement

This code snippet declares an integer variable 'age' and initializes it to 20. The 'if' statement checks if 'age' is greater than or equal to 18. If the condition is true, it prints "You are an adult." to the console.

package main

import "fmt"

func main() {
	age := 20

	if age >= 18 {
		fmt.Println("You are an adult.")
	}
}

Concepts Behind the Snippet

The core concept is conditional execution. The 'if' statement evaluates a boolean expression. If the expression is true, the code block within the 'if' statement's curly braces is executed. If it's false, the code block is skipped.

Real-Life Use Case

A common use case is validating user input. For example, checking if a user-provided age is a valid number before processing it further. Another use is authorization, where you check if a user has the correct permissions before allowing them to access certain resources.

Best Practices

  • Keep the boolean expression simple and easy to understand. Complex expressions can be hard to read and debug.
  • Ensure all variables used in the condition are properly initialized.
  • Consider using helper functions to encapsulate complex boolean logic.

Interview Tip

Be prepared to discuss different ways to structure 'if' statements, including 'if-else' and 'if-else if-else' chains. Also, understand the importance of code readability and maintainability when writing conditional logic.

When to use them

Use 'if' statements whenever you need to execute code conditionally based on a boolean condition. They are fundamental for decision-making in programs.

Memory footprint

The memory footprint of an 'if' statement itself is negligible. However, the memory footprint of the variables used in the condition and the code executed within the 'if' block needs to be considered, especially when dealing with large data structures.

FAQ

  • What happens if the condition in the 'if' statement is false?

    If the condition is false, the code block within the 'if' statement is skipped, and the program continues executing the code after the 'if' statement.
  • Can I nest 'if' statements?

    Yes, you can nest 'if' statements within other 'if' statements. This allows you to create more complex conditional logic. However, excessive nesting can make the code harder to read, so consider refactoring if nesting becomes too deep.