Go - Decision Making

Introduction to Decision Making in Go

Hello there, future Go programmer! Today, we're diving into one of the most crucial aspects of programming: decision making. Just like in real life, our programs need to make choices based on certain conditions. In Go, we have several tools at our disposal to implement these decisions. Let's embark on this exciting journey together!

Go - Decision Making

If Statement: The Basic Building Block

Syntax and Structure

The if statement is the foundation of decision making in Go. It allows us to execute a block of code only if a certain condition is true. Here's the basic structure:

if condition {
    // code to execute if condition is true
}

Let's look at a simple example:

package main

import "fmt"

func main() {
    age := 18

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

In this example, we're checking if the age is 18 or older. If it is, we print a message. Run this code, and you'll see the message because 18 is indeed greater than or equal to 18!

Adding an Else Clause

What if we want to do something when the condition is false? That's where the else clause comes in:

package main

import "fmt"

func main() {
    age := 16

    if age >= 18 {
        fmt.Println("You are eligible to vote!")
    } else {
        fmt.Println("Sorry, you're too young to vote.")
    }
}

Now, since age is 16, which is less than 18, the program will print the message in the else block.

If-Else If-Else Chain

Sometimes, we need to check multiple conditions. We can chain if-else statements like this:

package main

import "fmt"

func main() {
    score := 75

    if score >= 90 {
        fmt.Println("A grade")
    } else if score >= 80 {
        fmt.Println("B grade")
    } else if score >= 70 {
        fmt.Println("C grade")
    } else {
        fmt.Println("Need improvement")
    }
}

This program checks the score and prints the corresponding grade. With a score of 75, it will print "C grade".

Switch Statement: The Multi-Way Decision Maker

When you have multiple conditions to check, especially if they're all checking the same variable, the switch statement can make your code cleaner and more efficient.

Basic Switch Syntax

package main

import "fmt"

func main() {
    day := "Monday"

    switch day {
    case "Monday":
        fmt.Println("It's the start of the work week!")
    case "Friday":
        fmt.Println("TGIF!")
    default:
        fmt.Println("It's a regular day.")
    }
}

In this example, we check the value of day and execute the corresponding case. The default case is executed if none of the other cases match.

Switch with Multiple Cases

You can also group multiple cases together:

package main

import "fmt"

func main() {
    day := "Saturday"

    switch day {
    case "Monday", "Tuesday", "Wednesday", "Thursday", "Friday":
        fmt.Println("It's a weekday.")
    case "Saturday", "Sunday":
        fmt.Println("It's the weekend!")
    default:
        fmt.Println("Invalid day.")
    }
}

This code will print "It's the weekend!" because Saturday is one of the weekend days.

Switch without an Expression

Go allows you to use switch without an expression, which can be used as an alternative to long if-else chains:

package main

import "fmt"

func main() {
    score := 85

    switch {
    case score >= 90:
        fmt.Println("A grade")
    case score >= 80:
        fmt.Println("B grade")
    case score >= 70:
        fmt.Println("C grade")
    default:
        fmt.Println("Need improvement")
    }
}

This will print "B grade" because 85 is greater than or equal to 80.

Conditional Operators

To make our conditions more powerful, we use conditional operators. Here's a table of the most common ones:

Operator Description Example
== Equal to a == b
!= Not equal to a != b
< Less than a < b
> Greater than a > b
<= Less than or equal to a <= b
>= Greater than or equal to a >= b
&& Logical AND a && b
|| Logical OR a || b
! Logical NOT !a

Let's see these in action:

package main

import "fmt"

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

    if age >= 18 && hasLicense {
        fmt.Println("You can drive a car!")
    } else if age >= 18 && !hasLicense {
        fmt.Println("You're old enough, but you need a license.")
    } else {
        fmt.Println("You're too young to drive.")
    }
}

This program checks both the age and whether the person hasLicense to determine if they can drive.

Conclusion

Decision making is a fundamental concept in programming, and Go provides us with powerful tools to implement it. Remember, practice makes perfect! Try creating your own programs using if, switch, and different conditional operators.

As you continue your journey in Go, you'll find yourself using these constructs frequently. They're the building blocks of logic in your programs, helping your code make smart decisions based on different conditions.

Keep coding, keep learning, and most importantly, have fun with Go!

Credits: Image by storyset