0
0
Goprogramming~30 mins

Why defer is used in Go - See It in Action

Choose your learning style9 modes available
Why defer is used
📖 Scenario: Imagine you are writing a Go program that opens a file, reads some data, and then closes the file. You want to make sure the file is always closed properly, even if something goes wrong while reading.
🎯 Goal: You will learn how to use defer in Go to ensure a file is closed automatically at the right time, making your code safer and cleaner.
📋 What You'll Learn
Create a variable to open a file
Use defer to close the file
Read from the file
Print the read content
💡 Why This Matters
🌍 Real World
In real programs, resources like files or network connections must be closed properly to avoid problems. Using <code>defer</code> helps make sure this happens even if errors occur.
💼 Career
Understanding <code>defer</code> is important for writing safe and clean Go code, which is a valuable skill for backend development and systems programming jobs.
Progress0 / 4 steps
1
Open a file
Write code to open a file named example.txt using os.Open and assign it to a variable called file. Also handle the error by assigning it to err.
Go
Hint

Use os.Open("example.txt") and assign the results to file and err.

2
Use defer to close the file
Add a defer statement to call file.Close() right after opening the file to ensure it will be closed automatically when the function ends.
Go
Hint

Write defer file.Close() right after checking the error.

3
Read from the file
Create a byte slice called data with length 100. Use file.Read(data) to read from the file and assign the number of bytes read to n and error to err. Handle the error if it is not nil.
Go
Hint

Create data with make([]byte, 100) and read into it with file.Read(data).

4
Print the read content
Print the string version of the bytes read from the file using fmt.Println(string(data[:n])).
Go
Hint

Use fmt.Println(string(data[:n])) to print the content read.