Go from Zero 09. Errors Example

Word Count from File

Read a file and count word frequencies, combining file I/O with maps.

Sample sample.txt:

go is simple and go is fast
the best way to learn go is to write go

The Go program that reads and counts words:

package main

import (
	"fmt"
	"os"
	"strings"
)

func countWords(filename string) (map[string]int, error) {
	data, err := os.ReadFile(filename)
	if err != nil {
		return nil, err
	}

	words := strings.Fields(string(data))
	counts := map[string]int{}
	for _, w := range words {
		counts[strings.ToLower(w)]++
	}
	return counts, nil
}

func main() {
	counts, err := countWords("sample.txt")
	if err != nil {
		fmt.Println("Error:", err)
		return
	}

	fmt.Printf("Found %d unique words:\n", len(counts))
	for word, count := range counts {
		if count > 1 {
			fmt.Printf("  %s: %d\n", word, count)
		}
	}
}

💻 Run locally

Copy the code above and run it on your machine

© 2026 ByteLearn.dev. Free courses for developers. · Privacy