×

go · level 2 · unit 6 · lesson 2

  1. meet it
  2. guess first
  3. your turn
  4. fix it
  5. nailed it

Tap a green word if you get lost.

meet it

A reads a file, or typed input, line by line.

os.ReadFile grabs a whole file at once. For a long file, it is often better to work through it a line at a time. opens the file, and defer f.Close() makes sure it gets closed again.

scanner := bufio.NewScanner(f) makes a Scanner from the bufio toolbox. Each scanner.Scan() moves to the next line and gives true, or false when none are left. So for scanner.Scan() { loops once per line, and scanner.Text() is that line.

is the text typed into your program, and a Scanner reads it the same way: bufio.NewScanner(os.Stdin). Unlike fmt.Scan, it keeps the spaces, so it reads a whole sentence at once.

package main
import "bufio"
import "fmt"
import "os"
func main() {
	os.WriteFile("pets.txt", []byte("Rex the dog\nTibbles the cat\nGoldie the fish\n"), 0644)
	f, err := os.Open("pets.txt")
	if err != nil {
		fmt.Println("No pets file")
		return
	}
	defer f.Close()
	scanner := bufio.NewScanner(f)
	count := 0
	for scanner.Scan() {
		count++
		fmt.Printf("%d: %s\n", count, scanner.Text())
	}
}

for scanner.Scan() is the while loop you already know: a for with only a condition.