Let’s face it we have all been there. Those red lines, your app breaks, you begin to panic, you get all sweaty and feel like pulling your hair out. We hate errors. You can chase errors for days or even weeks. That is terrifying.
Something about Golang caught my attention and that is out of the box almost all functions return an error. Functions in Golang can have two return types.
In this very brief blog post, we will talk about how Golang hands Errors. I guarantee you will fall in love with it.
Let's go!
In Golang almost every function returns an error. Golang asks your function, "Did you encounter any errors while executing this task?"
Let's take a look at this in action. The code block below creates a folder in Golang
package main
import (
"fmt"
"os"
)
func main() {
folderName := "Your_Folder_Name" // Replace 'Your_Folder_Name' with the desired folder name
err := os.Mkdir(folderName, 0755) // Creates a directory with read/write/execute permissions for owner, and read/execute permissions for group and others
if err != nil {
fmt.Println("Error creating folder:", err)
return
}
fmt.Printf("Folder '%s' created successfully!\n", folderName)
}
Here is the Python equivalent of the same code
import os
folder_name = 'Your_Folder_Name' # Replace 'Your_Folder_Name' with the desired folder name
os.mkdir(folder_name)
print(f"Folder '{folder_name}' created successfully!")
Obvious to the keen eyes you will see that I have more lines of code in my Golang snippet than I do in Python.
I want to believe this is intentional by the people behind the Golang language.
I can imagine them saying we do not want any surprises at runtime or compiletime as the case may be.
In the Go program os.Mkdir() returns an error if something happens during the process of creating a directory whereas in the Python program, you really will not know what blew up.
I know what you thinking. You are screaming at me saying "The Python code can be modified with a Try Except to catch errors" You are right. But here you need to know what type of error will be returned.
import os
folder_name = 'Your_Folder_Name' # Replace 'Your_Folder_Name' with the desired folder name
try:
os.mkdir(folder_name)
print(f"Folder '{folder_name}' created successfully!")
except FileExistsError:
print(f"Folder '{folder_name}' already exists!")
This by far is one of my favorite features of Golang. I do not like the extra work that comes with Golang but It is worth it.