The os and io packages handle files and streams. Use defer f.Close() after os.Open—similar to try-with-resources patterns in Java.
Reading and writing
data, err := os.ReadFile("config.txt")
err = os.WriteFile("out.txt", data, 0644)
bufio.Scanner reads line-by-line efficiently. io.Copy streams large files without loading entirely into memory.
Paths
path/filepath joins paths portably—use instead of string concatenation for cross-platform tools.
Important interview questions and answers
- Q: defer Close importance?
A: Ensures file descriptors release even when errors occur mid-function. - Q: ReadFile vs Open?
A: ReadFile loads entire file—fine for small configs; Open+Copy for large streams.
Self-check
- Which package reads an entire file in Go 1.16+?
- Why use filepath.Join?
Tip: Always defer f.Close() after os.Open—like try-with-resources in Java.
Interview prep
- defer Close?
Releases file descriptors even when errors occur later in the function.
- ReadFile vs streaming?
ReadFile loads entire file—fine for small configs; io.Copy for large streams.