diff options
Diffstat (limited to 'libgo/go/bufio/example_test.go')
-rw-r--r-- | libgo/go/bufio/example_test.go | 29 |
1 files changed, 29 insertions, 0 deletions
diff --git a/libgo/go/bufio/example_test.go b/libgo/go/bufio/example_test.go index 3da9141..4666e6d 100644 --- a/libgo/go/bufio/example_test.go +++ b/libgo/go/bufio/example_test.go @@ -80,3 +80,32 @@ func ExampleScanner_custom() { // 5678 // Invalid input: strconv.ParseInt: parsing "1234567901234567890": value out of range } + +// Use a Scanner with a custom split function to parse a comma-separated +// list with an empty final value. +func ExampleScanner_emptyFinalToken() { + // Comma-separated list; last entry is empty. + const input = "1,2,3,4," + scanner := bufio.NewScanner(strings.NewReader(input)) + // Define a split function that separates on commas. + onComma := func(data []byte, atEOF bool) (advance int, token []byte, err error) { + for i := 0; i < len(data); i++ { + if data[i] == ',' { + return i + 1, data[:i], nil + } + } + // There is one final token to be delivered, which may be the empty string. + // Returning bufio.ErrFinalToken here tells Scan there are no more tokens after this + // but does not trigger an error to be returned from Scan itself. + return 0, data, bufio.ErrFinalToken + } + scanner.Split(onComma) + // Scan. + for scanner.Scan() { + fmt.Printf("%q ", scanner.Text()) + } + if err := scanner.Err(); err != nil { + fmt.Fprintln(os.Stderr, "reading input:", err) + } + // Output: "1" "2" "3" "4" "" +} |