Blog de programación, errores, soluciones

Chose Language:
Author: Admin/Publisher |finished | checked

If and else in Go Language

In this section, we’ll explore how to use if and else statements in Go.

Imagine an if statement as a way to say:
“If this condition is true, then do this.”

It’s like a simple decision-making tool in code. Let’s look at an example written in Go:

/*
In this case, 'elementos' will be 0 because we're explicitly setting it to 0.
But imagine it's the result of a database query that returns 0.
*/
elements := 0
if elements == 0 {
    println("no elements to display")
}

Continuing with this idea—let’s assume that elements is the number returned from a database query. If elements == 0, then we print:
“no elements to display”

On the same Go documentation page, there’s an example showing that you can declare a variable inside the if statement. We’ll take a look at that example next.

[C1] declaring a variable inside an if
if err := file.Chmod(0664); err != nil {
    log.Print(err)
    return err
}

Don’t worry about what we’re doing with file.Chmod—we’ll see what it does in future posts. Just remember, you can declare a variable inside an if statement and compare it.

This is equivalent to doing the following:

[C2] declaring a variable inside an if part 2
err := file.Chmod(0664)
if  err != nil {
    log.Print(err)
    return err
}

Take another look at the [C1] code. The ; symbol separates the variable declaration err := file.Chmod(0664) from the conditional check err != nil. This is a common pattern in Go, allowing both operations to be performed in a single if statement.

Another detail worth noting is that Go doesn’t require parentheses around the condition—if err != nil is perfectly valid without wrapping it in ().

if you are not secure that you can use () in go here you have an example that you can run in go playground:

Checking if if() works
package main

import "fmt"

func main() {
    err := doSomething()

    if (err != nil) {
        fmt.Println("Error occurred:", err)
    } else {
        fmt.Println("Everything went fine.")
    }
}

func doSomething() error {
    // Simulate an error — change this to 'nil' to see the other path
    return fmt.Errorf("simulated failure")
}

Checking if an Error Occurs in Go

The following Go code snippet is something you’ll often see:

if  err != nil { 
   //code
}

In this example, err is a variable typically used to store error values in Go. It’s short for “error” and is part of a common idiom in Go programming.

When the error is not nil, it indicates that an error has occurred. If the error is nil, it means there was no error.

Lets take a look to a simple but functional example in real life:

Example1
package main

import (
    "fmt"
    "os"
)

func main() {
    // Try to open a file
    file, err := os.Open("example.txt")

    // Check if an error occurred
    if err != nil {
        fmt.Println("Error opening file:", err)
        return
    }

    // If no error, proceed
    fmt.Println("File opened successfully:", file.Name())
    file.Close()
}

In this example, you can see a real-life situation where we attempt to open a file. If we can’t, the message ‘Error opening file’ will be displayed, and the function will exit using return, without triggering a panic.

Adding the else to the if

So far, we’ve learned how to check a single condition. But what happens when we need to evaluate multiple conditions?
This is where else and else if comes into play.

the following is an example of checking what OS you have:

Checking the OS with if/else
package main

import (
	"fmt"
	"runtime"
)

func main() {
	if runtime.GOOS == "windows" {
		fmt.Println("You are using Windows")
	} else if runtime.GOOS == "linux" {
		fmt.Println("You are using Linux")
	} else if runtime.GOOS == "darwin" {
		fmt.Println("You are using macOS")
	} else {
		fmt.Printf("Unknown operating system: %s\n", runtime.GOOS)
	}
}

Else if will allow you to check another condition while else is what happen when no one of the conditions match.

The else block is used to handle the alternative path—what happens if the previous condition isn’t true. It acts like a safety net, ensuring that your program still knows what to do when none of the if or else if conditions are met.

You can think of else as saying:

“If none of the above is true, then do this.”

Category: en-go
Something wrong? If you found an error or mistake in the content you can contact me on Twitter | @luisg2249_luis.
Recent articles