Practical Examples of Bufio Scanner Usage
The bufio.Scanner
in Golang is a versatile tool that can be applied to a wide range of input processing tasks. Let's explore a few practical examples to demonstrate its capabilities.
Reading from a File
One common use case for the bufio.Scanner
is reading data from a file. This can be particularly useful when working with large files, as the buffering mechanism of the bufio.Scanner
can help improve performance.
package main
import (
"bufio"
"fmt"
"os"
)
func main() {
file, _ := os.Open("input.txt")
defer file.Close()
scanner := bufio.NewScanner(file)
for scanner.Scan() {
line := scanner.Text()
fmt.Println(line)
}
if err := scanner.Err(); err != nil {
fmt.Fprintln(os.Stderr, "error:", err)
}
}
In this example, we create a bufio.Scanner
that reads from a file named "input.txt". The scanner.Scan()
method is used to read each line of the file, and the scanner.Text()
method retrieves the content of the current line.
Processing Command-Line Arguments
The bufio.Scanner
can also be used to process command-line arguments, which can be useful for building command-line tools or scripts.
package main
import (
"bufio"
"fmt"
"os"
)
func main() {
scanner := bufio.NewScanner(os.Stdin)
for scanner.Scan() {
arg := scanner.Text()
fmt.Println("Argument:", arg)
}
if err := scanner.Err(); err != nil {
fmt.Fprintln(os.Stderr, "error:", err)
}
}
In this example, the bufio.Scanner
reads input from the standard input (os.Stdin
), which allows the user to enter command-line arguments. Each argument is then printed to the console.
Parsing Delimited Data
The bufio.Scanner
can also be used to parse data that is delimited by a specific character or pattern, such as CSV or tab-separated files.
package main
import (
"bufio"
"fmt"
"os"
"strings"
)
func main() {
file, _ := os.Open("data.csv")
defer file.Close()
scanner := bufio.NewScanner(file)
scanner.Split(bufio.ScanLines)
for scanner.Scan() {
line := scanner.Text()
fields := strings.Split(line, ",")
fmt.Println("Fields:", fields)
}
if err := scanner.Err(); err != nil {
fmt.Fprintln(os.Stderr, "error:", err)
}
}
In this example, we create a bufio.Scanner
that reads from a CSV file named "data.csv". We configure the scanner to use the bufio.ScanLines
split function, which divides the input into individual lines. Then, we split each line by the comma character to extract the individual fields.
These examples demonstrate the versatility of the bufio.Scanner
and how it can be applied to a variety of input processing tasks in Golang. By leveraging its efficient buffering and customizable split functions, you can build robust and performant input processing solutions for your applications.