Source file
src/bufio/example_test.go
1
2
3
4
5 package bufio_test
6
7 import (
8 "bufio"
9 "fmt"
10 "os"
11 "strconv"
12 "strings"
13 )
14
15 func ExampleWriter() {
16 w := bufio.NewWriter(os.Stdout)
17 fmt.Fprint(w, "Hello, ")
18 fmt.Fprint(w, "world!")
19 w.Flush()
20
21 }
22
23 func ExampleWriter_AvailableBuffer() {
24 w := bufio.NewWriter(os.Stdout)
25 for _, i := range []int64{1, 2, 3, 4} {
26 b := w.AvailableBuffer()
27 b = strconv.AppendInt(b, i, 10)
28 b = append(b, ' ')
29 w.Write(b)
30 }
31 w.Flush()
32
33 }
34
35
36 func ExampleScanner_lines() {
37 scanner := bufio.NewScanner(os.Stdin)
38 for scanner.Scan() {
39 fmt.Println(scanner.Text())
40 }
41 if err := scanner.Err(); err != nil {
42 fmt.Fprintln(os.Stderr, "reading standard input:", err)
43 }
44 }
45
46
47 func ExampleScanner_Bytes() {
48 scanner := bufio.NewScanner(strings.NewReader("gopher"))
49 for scanner.Scan() {
50 fmt.Println(len(scanner.Bytes()) == 6)
51 }
52 if err := scanner.Err(); err != nil {
53 fmt.Fprintln(os.Stderr, "shouldn't see an error scanning a string")
54 }
55
56
57 }
58
59
60
61 func ExampleScanner_words() {
62
63 const input = "Now is the winter of our discontent,\nMade glorious summer by this sun of York.\n"
64 scanner := bufio.NewScanner(strings.NewReader(input))
65
66 scanner.Split(bufio.ScanWords)
67
68 count := 0
69 for scanner.Scan() {
70 count++
71 }
72 if err := scanner.Err(); err != nil {
73 fmt.Fprintln(os.Stderr, "reading input:", err)
74 }
75 fmt.Printf("%d\n", count)
76
77 }
78
79
80
81 func ExampleScanner_custom() {
82
83 const input = "1234 5678 1234567901234567890"
84 scanner := bufio.NewScanner(strings.NewReader(input))
85
86 split := func(data []byte, atEOF bool) (advance int, token []byte, err error) {
87 advance, token, err = bufio.ScanWords(data, atEOF)
88 if err == nil && token != nil {
89 _, err = strconv.ParseInt(string(token), 10, 32)
90 }
91 return
92 }
93
94 scanner.Split(split)
95
96 for scanner.Scan() {
97 fmt.Printf("%s\n", scanner.Text())
98 }
99
100 if err := scanner.Err(); err != nil {
101 fmt.Printf("Invalid input: %s", err)
102 }
103
104
105
106
107 }
108
109
110
111 func ExampleScanner_emptyFinalToken() {
112
113 const input = "1,2,3,4,"
114 scanner := bufio.NewScanner(strings.NewReader(input))
115
116 onComma := func(data []byte, atEOF bool) (advance int, token []byte, err error) {
117 for i := 0; i < len(data); i++ {
118 if data[i] == ',' {
119 return i + 1, data[:i], nil
120 }
121 }
122 if !atEOF {
123 return 0, nil, nil
124 }
125
126
127
128 return 0, data, bufio.ErrFinalToken
129 }
130 scanner.Split(onComma)
131
132 for scanner.Scan() {
133 fmt.Printf("%q ", scanner.Text())
134 }
135 if err := scanner.Err(); err != nil {
136 fmt.Fprintln(os.Stderr, "reading input:", err)
137 }
138
139 }
140
View as plain text