Sobes.tech
Junior — Middle

What is the role of the defer operator in Go and what are its advantages?

sobes.tech AI

Answer from AI

The defer operator in Go is used to postpone the execution of a function until the surrounding function exits (usually for resource cleanup or final actions).

Advantages of defer:

  • Ensures the code runs at the end of the function, even if the function exits with an error or panic.
  • Improves code readability by allowing resource release to be written next to their allocation.
  • Helps avoid code duplication for cleanup in different parts of the function.

Example:

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

    // work with the file
    return nil
}

Here, file.Close() will be called automatically when readFile exits, regardless of how the function terminates.