← All Exercises

Defer for Resource Cleanup

basicgo~10min

Background

Defer guarantees cleanup execution making resource management safer and more readable.

Problem

Use defer to close files and connections ensuring cleanup regardless of how the function exits.

Input

Resources to manage

Output

Guaranteed cleanup on exit

Sample tests

Sample 1

Input: defer file.Close()
Expected: file closed on return

Your solution

Learning objective

Learn resource management with defer in Go