Junior
What is the purpose of using the defer construct in Go?
sobes.tech AI
Answer from AI
The defer construct is used for deferred execution of a function or method. The scheduled function will be executed immediately before the surrounding function returns.
Main purposes of using defer:
- Resource release: Guaranteed closing of files, cleaning up network connections, releasing mutex locks and other system resources, even if a panic occurs in the code.
- Code simplification: Allows placing resource release code next to the code that acquires it, improving readability.
- Panic handling: In combination with
recover,defercan be used to intercept and handle panics.
Example of file release:
// Example of deferred file closing
file, err := os.Open("example.txt")
if err != nil {
// error handling
return
}
defer file.Close() // Guaranteed file closure upon function exit
// work with the file