// Chapter 33 example: main calls run, and turns its error into a message and // an exit code. Every deferred call in run has finished before os.Exit. // Build with: go build -o scores.exe exercises/33/06-run.go // Run with: go run exercises/33/06-run.go exercises/33/scores.txt package main import ( "bufio" "errors" "fmt" "os" "strconv" "strings" ) var errUsage = errors.New("wrong usage") func main() { err := run(os.Args[1:]) if errors.Is(err, errUsage) { fmt.Fprintln(os.Stderr, "usage: scores FILE") os.Exit(2) } if err != nil { fmt.Fprintln(os.Stderr, "scores:", err) os.Exit(1) } } // run does the whole job, and returns an error instead of exiting. func run(args []string) error { if len(args) != 1 { return errUsage } scores, err := parseScores(args[0]) if err != nil { return err } total := 0 for _, s := range scores { fmt.Printf("%-8s %3d\n", s.name, s.points) total += s.points } fmt.Printf("%-8s %3d\n", "Total", total) return nil } // parseError reports a line in a scores file that could not be read. type parseError struct { file string line int problem string } func (e parseError) Error() string { return fmt.Sprintf("%s:%d: %s", e.file, e.line, e.problem) } type score struct { name string points int } // parseScores reads a file with one "name points" pair per line. // Empty lines are skipped. func parseScores(name string) ([]score, error) { f, err := os.Open(name) if err != nil { return nil, err } defer f.Close() scores := []score{} number := 0 scanner := bufio.NewScanner(f) for scanner.Scan() { number++ line := strings.TrimSpace(scanner.Text()) if line == "" { continue } fields := strings.Fields(line) if len(fields) != 2 { return nil, parseError{file: name, line: number, problem: "want a name and a score"} } points, err := strconv.Atoi(fields[1]) if err != nil { problem := fmt.Sprintf("score %q is not a whole number", fields[1]) return nil, parseError{file: name, line: number, problem: problem} } scores = append(scores, score{name: fields[0], points: points}) } return scores, scanner.Err() }