// A ParseError indicates an error in converting a word into an integer. type ParseError struct { Index int// The index into the space-separated list of words. Word string// The word that generated the parse error. Err error// The raw error that precipitated this error, if any. }
// Parse parses the space-separated words in in put as integers. funcParse(input string) (numbers []int, err error) { deferfunc() { if r := recover(); r != nil { var ok bool err, ok = r.(error) if !ok { err = fmt.Errorf("pkg: %v", r) } } }()
for _, ex := range examples { fmt.Printf("Parsing %q:\n ", ex) nums, err := parse.Parse(ex) if err != nil { fmt.Println(err) // here String() method from ParseError is used continue } fmt.Println(nums) } }
输出:
1 2 3 4 5 6 7 8 9 10
Parsing "1 2 3 4 5": [1 2 3 4 5] Parsing "100 50 25 12.5 6.25": pkg: pkg parse: error parsing "12.5" as int Parsing "2 + 2 = 4": pkg: pkg parse: error parsing "+" as int Parsing "1st class": pkg: pkg parse: error parsing "1st" as int Parsing "": pkg: no words to parse