Analyze the following Go code. Is the error handling and resource management approach correct?

Go & Rust interview question for Advanced practice.

Answer

Yes, the code is correct and demonstrates idiomatic Go for this task.

Explanation

The code is correct and idiomatic. Option A is incorrect because the if err != nil block causes an immediate return, so the defer statement is never reached if os.Open fails. Option C is technically true (file.Close() can return an error), but for a read-only operation, it is common and acceptable practice in Go to ignore this error. The primary goal is to release the file handle, which defer guarantees. Therefore, the overall pattern is considered correct.

Related Questions