@dev.by.jacobSave and share! :)

Learn Go by Example

If/Else

Conditional Statements

Series image
@dev.by.jacobSave and share! :)

Overview

Conditional statements in Go, such as if and else, allow you to execute different blocks of code based on certain conditions.

As in other languages, this helps in controlling the flow of your program.

See the below for an example of using if and else in Go.

@dev.by.jacobSave and share! :)

Code

package main

import "fmt";

func main() {
   x := 10
   y := 20

   if x < y {
      fmt.Println("x is less than y")
   } else if x > y {
      fmt.Println("x is greater than y")
   } else {
      fmt.Println("x is equal to y")
   }

    // Short statement with if
   if z := x + y; z > 20 {
      fmt.Println("z is greater than 20")
   } else {
      fmt.Println("z is not greater than 20")
   }
}
@dev.by.jacobSave and share! :)

Explanation

Step-by-Step:

  1. Basic If Statement:

    if x < y checks if x is less than y and executes the corresponding block.

  2. Else If Statement:

    else if x > y checks if x is greater than y and executes the corresponding block if true.

  3. Else Statement:

    else executes if none of the previous conditions are met.

  4. Short Statement with If:

    if z := x + y; z > 20 declares and initializes z within the if statement and checks if z is greater than 20.

@dev.by.jacobSave and share! :)

Summary

If and else statements are used to execute different blocks of code based on certain conditions.

In Go, you can also use a short statement with if to declare and initialize variables within the if statement.

Otherwise, the syntax for if and else in Go is similar to other languages.

FOLLOW

for daily software breakdowns!