Go from Beginner to Expert: A Complete Guide to Learn Golang PART-19 Step-by-Step Guide to understand File I/O and Error Handling in Golang.

Go from Beginner to Expert: A Complete Guide to Learn Golang PART-19

Step-by-Step Guide to understand File I/O and Error Handling in Golang.

Md. Faiyaj Zaman
4 min readMar 17, 2023

--

Hey there! In this tutorial, we’re going to talk about file I/O and error handling in Golang. We’ll first explore how to read and write files in Golang and then we’ll take a look at error handling and how to handle errors in your code.

By the end of this tutorial, you’ll have a good understanding of these two important concepts and how to implement them in your own Golang code.

Please check out the previous Step-by-Step Guide to understand Structs in Golang.

File I/O in Golang

Let’s start by understanding file I/O in Golang. File I/O, or input/output, is the process of reading and writing data to and from files. In Golang, we can perform file I/O using the “os” and “bufio” packages.

To open a file in Golang, we use the “os.Open” function, which takes the file name and mode as arguments. The mode specifies whether we want to open the file for reading, writing, or both. Here’s an example of how to open a file for reading:

file, err := os.Open("example.txt")

if err != nil {

log.Fatal(err)

}

defer file.Close()

In this code snippet, we’re opening a file called “example.txt” for reading. If there’s an error opening the file, we’re logging the error and exiting the program. We’re also using the “defer” keyword to ensure that the file is closed after we’re done with it.

Once we have a file open, we can read its contents using a “bufio.Scanner” object. Here’s an example of how to read the contents of a file line by line:

scanner := bufio.NewScanner(file)

for scanner.Scan() {

fmt.Println(scanner.Text())

}

if err := scanner.Err(); err != nil {

log.Fatal(err)

}

In this code snippet, we’re creating a “bufio.Scanner” object to read the contents of the file. We’re then using a “for” loop to read each line of the file and print it to the console. Finally, we’re checking if there were any errors while reading the file.

We can also write data to a file using the “os.Create” function, which takes the file name as an argument. Here’s an example of how to write data to a file:

file, err := os.Create("output.txt")

if err != nil {

log.Fatal(err)

}

defer file.Close()

file.WriteString("Hello, world!")

In this code snippet, we’re creating a file called “output.txt” for writing. If there’s an error creating the file, we’re logging the error and exiting the program.

We’re also using the “defer” keyword to ensure that the file is closed after we’re done with it. Finally, we’re using the “WriteString” method to write the string “Hello, world!” to the file.

Error Handling in Golang

Now that we’ve covered file I/O in Golang, let’s talk about error handling. In Golang, errors are represented by the “error” interface, which has a single method called “Error” that returns a string describing the error.

When a function encounters an error, it can return the error as a value. The calling function can then check if the error value is nil to see if there was an error. Here’s an example of how to return an error from a function:

func divide(x, y float64) (float64, error) {

if y == 0 {

return 0, fmt.Errorf("division by zero")

}

return x / y, nil

}

In this code snippet, we’re defining a function called “divide” that takes two float64 arguments, x and y, and returns the result of dividing x by y.

However, before performing the division, we’re checking if y is equal to 0. If it is, we’re returning an error using the “fmt.Errorf” function.

Now, let’s see how we can handle errors in our code. One way to handle errors is by using the “if err != nil” construct. Here’s an example of how to handle errors when calling the “divide” function:

result, err := divide(10.0, 0.0)

if err != nil {

log.Fatal(err)

}

fmt.Println(result)

In this code snippet, we’re calling the “divide” function with arguments 10.0 and 0.0. If there’s an error returned by the function, we’re logging the error and exiting the program. If there’s no error, we’re printing the result to the console.

Another way to handle errors is by using the “defer” keyword along with a function that handles the error. Here’s an example:

file, err := os.Open("example.txt")

if err != nil {

log.Fatal(err)

}

defer func() {

if err := file.Close(); err != nil {

log.Fatal(err)

}

}()

In this code snippet, we’re opening a file called “example.txt” for reading. If there’s an error opening the file, we’re logging the error and exiting the program.

We’re also using the “defer” keyword to ensure that the file is closed after we’re done with it. However, instead of just using “defer file.Close()”, we’re using an anonymous function that calls “file.Close()” and handles any errors that may occur.

In this tutorial, we’ve covered file I/O and error handling in Golang. We’ve learned how to read and write files using the “os” and “bufio” packages, and how to handle errors using the “error” interface and the “if err != nil” construct.

We’ve also seen how to use the “defer” keyword to ensure that resources are properly cleaned up. With this knowledge, you’ll be able to write Golang programs that can handle file I/O and errors gracefully.

If you want to Build web applications in Golang, Please check the next step step guide.

Thanks for reading!

--

--