Complete the code to ensure the file is closed after opening it.
file, err := os.Open("example.txt") if err != nil { log.Fatal(err) } [1] file.Close()
The defer keyword schedules the file.Close() call to run after the surrounding function finishes, ensuring the file is closed properly.
Complete the code to print 'Done' after the function finishes.
func process() {
[1] fmt.Println("Done")
fmt.Println("Processing...")
}Using defer before fmt.Println("Done") delays printing 'Done' until process finishes.
Fix the error by completing the code to close the database connection after use.
func queryDB() {
db, err := sql.Open("driver", "source")
if err != nil {
log.Fatal(err)
}
[1] db.Close()
// perform queries
}defer ensures db.Close() runs after queryDB finishes, properly closing the connection.
Fill both blanks to defer closing the file and unlocking the mutex.
func safeWrite() {
mu.Lock()
[1] mu.Unlock()
file, err := os.Create("data.txt")
if err != nil {
log.Fatal(err)
}
[2] file.Close()
// write data
}Using defer before mu.Unlock() and file.Close() ensures both run after safeWrite finishes, keeping code safe and clean.
Fill all three blanks to defer closing the file, unlocking the mutex, and printing 'Finished'.
func processFile() {
mu.Lock()
[1] mu.Unlock()
file, err := os.Open("file.txt")
if err != nil {
log.Fatal(err)
}
[2] file.Close()
[3] fmt.Println("Finished")
// process file
}All three calls are deferred to run after processFile ends, ensuring proper cleanup and final message.