Deferred Function Execution Cleanup

GoGoBeginner
Practice Now

This tutorial is from open-source community. Access the source code

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.


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL go(("`Go`")) -.-> go/ErrorHandlingGroup(["`Error Handling`"]) go/ErrorHandlingGroup -.-> go/defer("`Defer`") subgraph Lab Skills go/defer -.-> lab-15387{{"`Deferred Function Execution Cleanup`"}} end

Defer

In this challenge, you need to use defer to create a file, write to it, and then close it when you're done.

Requirements

  • The createFile function should create a file with the given path and return a pointer to the file.
  • The writeFile function should write the string "data" to the file.
  • The closeFile function should close the file and check for errors.

Example

## Running the program confirms that the file is closed
## after being written.
$ go run defer.go
creating
writing
closing

Summary

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.

Other Go Tutorials you may like