Control Structures

Hey! If you love Go and building Go apps as much as I do, let's connect on Twitter or LinkedIn. I talk about this stuff all the time!

Want to learn how to build better Go applications faster and easier? You can.

Check out my course on the Go Standard Library. You can check it out now for free.


Controlling the Flow: Making Your Code Do What You Want

Importance: Control structures are the backbone of any programming language. They allow you to control the flow of execution in your code, essentially telling it what to do and in which order.

Why it matters:

Imagine writing a recipe. You wouldn’t just list all the ingredients and then say “now mix everything together.” You’d need instructions outlining the steps:

  • Adding flour and sugar? This is like using a for loop to iterate through a set of steps, allowing you to use a sequence of actions repeatedly.
  • Think about it - your code needs to follow specific logic to perform tasks and produce meaningful results. Without control structures, your program would just run all its lines sequentially, with no way to make decisions or handle different situations differently.

Introduction:

Control structures are essential tools in Go (and any programming language) that allow you to dictate the flow of execution within your code. Essentially, they are the “if-then-else” statements and loops that control what parts of your code run when.

In Go, there are several types of control structures:

  • Conditional Statements: These let your program make decisions based on specific conditions.
  • Loops: Loops allow your code to repeat a block of code multiple times.

Example: Decision Making with if Statements

Let’s look at an example of a function in Go that uses “if” statements to check if a number is even or odd:

func isEven(number int) bool {
  return number%2 == 0
}

// Example usage
number := 10

if isEven(number) {
  fmt.Println("The number is even.")
} else {
  fmt.Println("The number is odd.")
}

Explanation:

  • In Go, you use the if keyword to create a conditional statement.

Typical Mistakes:

Beginners often forget that “if” statements need a condition and code blocks. They might write something like this:

// Incorrect: This "if" statement is missing the code block for the 'then' part.
if number % 2 == 0 {
  // Missing code block here
} else {
  fmt.Println("The number is odd.")
}

Code Structure:

  • Why use if instead of just comparing? Go’s “if” statements are powerful for controlling the flow of your code.

Go’s if statement can be used with a boolean expression:

  • Conditions: The ‘if’ statement checks if a condition is true or false.
  • Statements: The code block following the if statement will only run if the condition evaluates to true. If the code block is omitted, the program won’t know what to do based on the condition.

Why use if statements?

“If” statements allow your code to be smart and make decisions. They are essential for:

  • Making choices:

    You can choose which path of code to execute based on a condition (e.g., “if” a number is even, print “Even” otherwise, print “Odd”).

  • Handling errors:

    “If” statements are crucial for checking if something has gone wrong and executing appropriate code. For example:

func divide(a int, b int) (int, error) {
  if b == 0 {
    return 0, fmt.Errorf("Cannot divide by zero")
  } else {
    return a / b, nil
  }
}

Demonstrating the if Statement:

Let’s say you want to write a program that determines the price of a product based on whether it is discounted or not.

productPrice := 100.00

// Check for discount (example: "Is this product on sale?")
salePrice := 0.0

if saleProduct {
  // Calculate discounted price
  discountPercentage := 20.0 // Example: 20% discount
  salePrice = productPrice * 0.80 // Example: Apply 80% of the original price if it's a sale item

} else {
  // If not on sale, use the original price
  productPrice = productPrice * 1.05 // Example: Apply 5% discount

}

Explanation:

  • The code snippet uses an if statement to check for a condition:

    productPrice := 100.0 (This is where you’d define the ‘discount’ variable)

  • For example, if productPrice is defined as a variable that can be assigned a value of “on sale” or “not on sale”, this code shows the basic structure for setting the price based on the condition:

package main

import "fmt"

func main() {
  var price float64 = 100.00
  if productPrice > 50.00 {
    price := 100 * 1.20 // Original price with a discount multiplier
  } else {
    price := 100 * 1.0 // Original price
  }

  // Print the price
  fmt.Println("Product Price:", price)

Go := 100.00
if salePrice == true {
productPrice := productPrice * 0.80
} else {
productPrice := productPrice * 0.80

// Calculating the price with a discount
}

Understanding Conditional Statements:

  • In if statements, we use ‘if’, ‘else if’ and ‘else’ keywords to control the flow of execution.

  • The if statement is used to evaluate conditions.

  • Example: Imagine a user wants to buy a product.

Tips for Writing Efficient and Readable Conditional Statements:

  • Keep it simple: Use clear and concise conditions in your if statements. For example, instead of using a complex condition like “if (price >= 50) and (quantity > 10)” you can write multiple simpler ‘if’ statements.

  • Use the ‘else if’ and ‘else’ keywords effectively: You can use them to create different paths for your code depending on the conditions, or to define a default behavior.

  • Choose the right syntax: if statements are generally used to decide between two or more options. For example:

productPrice := 100.0 // Example: Define a 'sale price' variable that's only true if there is a discount

// If the product is on sale, apply the discount
if b == "true" {

  // Apply a discount to the price
  discount := 0.20
  price = price * discount

} else {
  // If not on sale, use the original price
  productPrice := 100.00 // Product is 100
  if (discount == true) {
    productPrice := productPrice * 0.80
  } else {
    // ...
    // Use this code for the 'else' part

      price := productPrice * 1.20 // Apply a 20% discount

  • Using if Statements Effectively:

    • Clarity: Use descriptive variable names (e.t. “isDiscounted” instead of “b”) and avoid nesting too many conditions, which can make the code hard to read.
    • Readability: Write clear and concise ‘if’ statements with meaningful conditions and actions.

Example: Defining a Function for Price Calculation

// Example:


Stay up to date on the latest in Coding for AI and Data Science

Intuit Mailchimp