Sobes.tech
Junior — Middle

Kas saaksite selgitada defer-i konstruktsiooni tööpõhimõtet ja kasutamist Go keeles?

sobes.tech AI

Vastus AI-lt

In Go, the keyword defer is used to delay the execution of a function: it will be executed 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(filename string) error {
    file, err := os.Open(filename)
    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 write cleaner and safer code, ensuring the execution of important finalization actions.