Senior
Why did you use the defer keyword?
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 useful for releasing resources, closing files, unlocking mutexes, and other cleanup operations.
For example, if you open a file, you can use defer to ensure it gets closed even if an error occurs or the function exits early:
func readFile(filename string) error {
file, err := os.Open(filename)
if err != nil {
return err
}
defer file.Close() // Will close when the function exits
// work with the file
return nil
}
Thus, defer helps write cleaner and safer code, reducing the likelihood of resource leaks.