// Chapter 33 example: an error type that carries the file and line, and // errors.As to get it back. // Run with: go run exercises/33/04-custom-type.go package main import ( "bufio" "errors" "fmt" "os" "strconv" "strings" ) // 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() } func report(name string) { scores, err := parseScores(name) if err != nil { fmt.Println("Error:", err) var pe parseError if errors.As(err, &pe) { fmt.Printf("Open %s and fix line %d.\n", pe.file, pe.line) } return } total := 0 for _, s := range scores { total += s.points } fmt.Printf("%s: %d players, %d points\n", name, len(scores), total) } func main() { report("exercises/33/scores.txt") report("exercises/33/bad-scores.txt") report("exercises/33/no-such-file.txt") }