Lesson 10 of 60 · Go
Working with Files & I/O
Duration: 20 minutes
File I/O
This lesson explains the main concept clearly with beginner-friendly examples and background so you can learn why the code works.
The os and io packages provide the building blocks for reading and writing.
// Write a string to a file
f, err := os.Create("out.txt")
if err != nil { log.Fatal(err) }
defer f.Close()
_, err = f.WriteString("Hello, Go!\n")
Buffered I/O
buf := bufio.NewReader(f)
line, err := buf.ReadString('\n')
Working with JSON
type Config struct {
Port int `json:"port"`
Debug bool `json:"debug"`
}
var cfg Config
data, _ := os.ReadFile("config.json")
json.Unmarshal(data, &cfg)
Copying files (one‑liner)
io.Copy(dst, src) // src and dst must implement io.Reader / io.Writer