Senior
What is the practical use of the keyword defer?
sobes.tech AI
Answer from AI
The defer keyword in Go is used to postpone the execution of a function until the current function exits. This is convenient for guaranteed resource release, closing files, unlocking mutexes, and other cleanup operations.
Example:
func readFile(filename string) error {
file, err := os.Open(filename)
if err != nil {
return err
}
defer file.Close() // the file will be closed when the function exits
// work with the file
// ...
return nil
}
defer simplifies resource management and makes the code more readable and safe, preventing leaks.