Using defer to close an open file

Report a typo

Below you will see a small Go program that creates a file hello.txt and then writes a string to it:

func main() {
    // 1
    file, err := os.Create("hello.txt")
    if err != nil {
        log.Fatal(err)
        // 2
    }
    // 3    

    if _, err := fmt.Fprintln(file, "Hello, JB Academy!"); err != nil {
        log.Fatal(err)
    }
    // 4
}

Please select which one of the commented lines is the most appropriate to add the defer file.Close() statement to.

Select one option from the list
___

Create a free account to access the full topic