Skip to content
Learn Netverks

Lesson

Step 27/36 75% through track

file-io-go

File I/O

Last reviewed Jun 1, 2026 Content v20260601
Track mode
server_compiled
Means
Compiled runner
Reading
~1 min
Level
intermediate

This lesson

This lesson teaches File I/O: the syntax, patterns, and safety habits you need before advancing in Go.

Teams still ship File I/O in Go codebases—skipping it leaves gaps in debugging and code reviews.

You will apply File I/O in contexts like: Kubernetes ecosystem tools, cloud APIs, and CLI utilities.

Write Go in main.go with package main and func main(), click Run on server—the dev runner runs go run main.go; use fmt.Println for output (requires Go toolchain; LEARNING_RUNNER_ENABLED=true).

When you can explain the previous lesson's ideas without copying starter code.

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

  1. Q: defer Close importance?
    A: Ensures file descriptors release even when errors occur mid-function.
  2. Q: ReadFile vs Open?
    A: ReadFile loads entire file—fine for small configs; Open+Copy for large streams.

Self-check

  1. Which package reads an entire file in Go 1.16+?
  2. 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.

Interview tip Lesson completion confidence

Can you explain this lesson in 30 seconds without reading notes?

Not saved yet.

Playground

Runs on the configured server runner (dev: npm run runner with LEARNING_RUNNER_ENABLED=true). Output appears below the editor.

Check yourself

Multiple choice — immediate feedback.

Discussion

Past discussion is visible to everyone. Only logged-in users can post comments and replies.

Starter discussion topics

  • defer close?
  • os.ReadFile?

Sign up or log in to post comments and sync lesson progress across devices.

No discussion yet. Be the first to ask a question.

Jump