example_test.go 3.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139
  1. // Copyright 2013 The Go Authors. All rights reserved.
  2. // Use of this source code is governed by a BSD-style
  3. // license that can be found in the LICENSE file.
  4. package bufio_test
  5. import (
  6. "bufio"
  7. "fmt"
  8. "os"
  9. "strconv"
  10. "strings"
  11. )
  12. func ExampleWriter() {
  13. w := bufio.NewWriter(os.Stdout)
  14. fmt.Fprint(w, "Hello, ")
  15. fmt.Fprint(w, "world!")
  16. w.Flush() // Don't forget to flush!
  17. // Output: Hello, world!
  18. }
  19. func ExampleWriter_AvailableBuffer() {
  20. w := bufio.NewWriter(os.Stdout)
  21. for _, i := range []int64{1, 2, 3, 4} {
  22. b := w.AvailableBuffer()
  23. b = strconv.AppendInt(b, i, 10)
  24. b = append(b, ' ')
  25. w.Write(b)
  26. }
  27. w.Flush()
  28. // Output: 1 2 3 4
  29. }
  30. // The simplest use of a Scanner, to read standard input as a set of lines.
  31. func ExampleScanner_lines() {
  32. scanner := bufio.NewScanner(os.Stdin)
  33. for scanner.Scan() {
  34. fmt.Println(scanner.Text()) // Println will add back the final '\n'
  35. }
  36. if err := scanner.Err(); err != nil {
  37. fmt.Fprintln(os.Stderr, "reading standard input:", err)
  38. }
  39. }
  40. // Return the most recent call to Scan as a []byte.
  41. func ExampleScanner_Bytes() {
  42. scanner := bufio.NewScanner(strings.NewReader("gopher"))
  43. for scanner.Scan() {
  44. fmt.Println(len(scanner.Bytes()) == 6)
  45. }
  46. if err := scanner.Err(); err != nil {
  47. fmt.Fprintln(os.Stderr, "shouldn't see an error scanning a string")
  48. }
  49. // Output:
  50. // true
  51. }
  52. // Use a Scanner to implement a simple word-count utility by scanning the
  53. // input as a sequence of space-delimited tokens.
  54. func ExampleScanner_words() {
  55. // An artificial input source.
  56. const input = "Now is the winter of our discontent,\nMade glorious summer by this sun of York.\n"
  57. scanner := bufio.NewScanner(strings.NewReader(input))
  58. // Set the split function for the scanning operation.
  59. scanner.Split(bufio.ScanWords)
  60. // Count the words.
  61. count := 0
  62. for scanner.Scan() {
  63. count++
  64. }
  65. if err := scanner.Err(); err != nil {
  66. fmt.Fprintln(os.Stderr, "reading input:", err)
  67. }
  68. fmt.Printf("%d\n", count)
  69. // Output: 15
  70. }
  71. // Use a Scanner with a custom split function (built by wrapping ScanWords) to validate
  72. // 32-bit decimal input.
  73. func ExampleScanner_custom() {
  74. // An artificial input source.
  75. const input = "1234 5678 1234567901234567890"
  76. scanner := bufio.NewScanner(strings.NewReader(input))
  77. // Create a custom split function by wrapping the existing ScanWords function.
  78. split := func(data []byte, atEOF bool) (advance int, token []byte, err error) {
  79. advance, token, err = bufio.ScanWords(data, atEOF)
  80. if err == nil && token != nil {
  81. _, err = strconv.ParseInt(string(token), 10, 32)
  82. }
  83. return
  84. }
  85. // Set the split function for the scanning operation.
  86. scanner.Split(split)
  87. // Validate the input
  88. for scanner.Scan() {
  89. fmt.Printf("%s\n", scanner.Text())
  90. }
  91. if err := scanner.Err(); err != nil {
  92. fmt.Printf("Invalid input: %s", err)
  93. }
  94. // Output:
  95. // 1234
  96. // 5678
  97. // Invalid input: strconv.ParseInt: parsing "1234567901234567890": value out of range
  98. }
  99. // Use a Scanner with a custom split function to parse a comma-separated
  100. // list with an empty final value.
  101. func ExampleScanner_emptyFinalToken() {
  102. // Comma-separated list; last entry is empty.
  103. const input = "1,2,3,4,"
  104. scanner := bufio.NewScanner(strings.NewReader(input))
  105. // Define a split function that separates on commas.
  106. onComma := func(data []byte, atEOF bool) (advance int, token []byte, err error) {
  107. for i := 0; i < len(data); i++ {
  108. if data[i] == ',' {
  109. return i + 1, data[:i], nil
  110. }
  111. }
  112. if !atEOF {
  113. return 0, nil, nil
  114. }
  115. // There is one final token to be delivered, which may be the empty string.
  116. // Returning bufio.ErrFinalToken here tells Scan there are no more tokens after this
  117. // but does not trigger an error to be returned from Scan itself.
  118. return 0, data, bufio.ErrFinalToken
  119. }
  120. scanner.Split(onComma)
  121. // Scan.
  122. for scanner.Scan() {
  123. fmt.Printf("%q ", scanner.Text())
  124. }
  125. if err := scanner.Err(); err != nil {
  126. fmt.Fprintln(os.Stderr, "reading input:", err)
  127. }
  128. // Output: "1" "2" "3" "4" ""
  129. }