Middle
Mis on defer Go-s ja millal see kutsutakse?
sobes.tech AI
Vastus AI-lt
In Go, the keyword defer is used to delay the invocation of a function: it will be executed after the surrounding function has completed, but before it exits.
This is useful for releasing resources, closing files, unlocking mutexes, and other cleanup operations, ensuring they happen even in case of errors or panics.
Example:
func readFile() {
file, err := os.Open("file.txt")
if err != nil {
log.Fatal(err)
}
defer file.Close() // the file will be closed at the end of the function
// work with the file
}
Here, file.Close() will be called automatically upon exiting readFile, regardless of how the function ends.