...
Run Format

Source file src/bufio/example_test.go

Documentation: bufio

     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  
     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() // Don't forget to flush!
    20  	// Output: Hello, world!
    21  }
    22  
    23  // The simplest use of a Scanner, to read standard input as a set of lines.
    24  func ExampleScanner_lines() {
    25  	scanner := bufio.NewScanner(os.Stdin)
    26  	for scanner.Scan() {
    27  		fmt.Println(scanner.Text()) // Println will add back the final '\n'
    28  	}
    29  	if err := scanner.Err(); err != nil {
    30  		fmt.Fprintln(os.Stderr, "reading standard input:", err)
    31  	}
    32  }
    33  
    34  // Use a Scanner to implement a simple word-count utility by scanning the
    35  // input as a sequence of space-delimited tokens.
    36  func ExampleScanner_words() {
    37  	// An artificial input source.
    38  	const input = "Now is the winter of our discontent,\nMade glorious summer by this sun of York.\n"
    39  	scanner := bufio.NewScanner(strings.NewReader(input))
    40  	// Set the split function for the scanning operation.
    41  	scanner.Split(bufio.ScanWords)
    42  	// Count the words.
    43  	count := 0
    44  	for scanner.Scan() {
    45  		count++
    46  	}
    47  	if err := scanner.Err(); err != nil {
    48  		fmt.Fprintln(os.Stderr, "reading input:", err)
    49  	}
    50  	fmt.Printf("%d\n", count)
    51  	// Output: 15
    52  }
    53  
    54  // Use a Scanner with a custom split function (built by wrapping ScanWords) to validate
    55  // 32-bit decimal input.
    56  func ExampleScanner_custom() {
    57  	// An artificial input source.
    58  	const input = "1234 5678 1234567901234567890"
    59  	scanner := bufio.NewScanner(strings.NewReader(input))
    60  	// Create a custom split function by wrapping the existing ScanWords function.
    61  	split := func(data []byte, atEOF bool) (advance int, token []byte, err error) {
    62  		advance, token, err = bufio.ScanWords(data, atEOF)
    63  		if err == nil && token != nil {
    64  			_, err = strconv.ParseInt(string(token), 10, 32)
    65  		}
    66  		return
    67  	}
    68  	// Set the split function for the scanning operation.
    69  	scanner.Split(split)
    70  	// Validate the input
    71  	for scanner.Scan() {
    72  		fmt.Printf("%s\n", scanner.Text())
    73  	}
    74  
    75  	if err := scanner.Err(); err != nil {
    76  		fmt.Printf("Invalid input: %s", err)
    77  	}
    78  	// Output:
    79  	// 1234
    80  	// 5678
    81  	// Invalid input: strconv.ParseInt: parsing "1234567901234567890": value out of range
    82  }
    83  
    84  // Use a Scanner with a custom split function to parse a comma-separated
    85  // list with an empty final value.
    86  func ExampleScanner_emptyFinalToken() {
    87  	// Comma-separated list; last entry is empty.
    88  	const input = "1,2,3,4,"
    89  	scanner := bufio.NewScanner(strings.NewReader(input))
    90  	// Define a split function that separates on commas.
    91  	onComma := func(data []byte, atEOF bool) (advance int, token []byte, err error) {
    92  		for i := 0; i < len(data); i++ {
    93  			if data[i] == ',' {
    94  				return i + 1, data[:i], nil
    95  			}
    96  		}
    97  		// There is one final token to be delivered, which may be the empty string.
    98  		// Returning bufio.ErrFinalToken here tells Scan there are no more tokens after this
    99  		// but does not trigger an error to be returned from Scan itself.
   100  		return 0, data, bufio.ErrFinalToken
   101  	}
   102  	scanner.Split(onComma)
   103  	// Scan.
   104  	for scanner.Scan() {
   105  		fmt.Printf("%q ", scanner.Text())
   106  	}
   107  	if err := scanner.Err(); err != nil {
   108  		fmt.Fprintln(os.Stderr, "reading input:", err)
   109  	}
   110  	// Output: "1" "2" "3" "4" ""
   111  }
   112  

View as plain text