Introduction
The defer
statement is used to delay the execution of a function until the surrounding function returns. It is often used to ensure that some cleanup is performed after a function completes, regardless of the path taken to get there.
This tutorial is from open-source community. Access the source code
The defer
statement is used to delay the execution of a function until the surrounding function returns. It is often used to ensure that some cleanup is performed after a function completes, regardless of the path taken to get there.
In this challenge, you need to use defer
to create a file, write to it, and then close it when you're done.
createFile
function should create a file with the given path and return a pointer to the file.writeFile
function should write the string "data" to the file.closeFile
function should close the file and check for errors.## Running the program confirms that the file is closed
## after being written.
$ go run defer.go
creating
writing
closing
In this challenge, you learned how to use defer
to ensure that a function call is performed later in a program's execution, usually for purposes of cleanup. You also learned how to create a file, write to it, and then close it using defer
.