Sobes.tech
Junior

Millist rolli mängib konstruktsioon defer Go keeles?

sobes.tech AI

Vastus AI-lt

In the Go language, the defer construct is used to delay the execution of a function — it will be called at the moment of exiting the current function, regardless of how the exit occurs (normally or due to an error).

This is useful for releasing resources, closing files, unlocking mutexes, and other cleanup operations.

Example:

func readFile() error {
    file, err := os.Open("file.txt")
    if err != nil {
        return err
    }
    defer file.Close() // the file will be closed upon exiting the function

    // work with the file
    return nil
}

Thus, defer helps ensure the execution of important final actions, improving resource management and error handling.