Streams
Examples
Filter
Here’s an example line filter in Go that writes a capitalized version of all input text. You can use this pattern to write your own Go line filters.
package main
import (
"bufio"
"fmt"
"os"
"strings"
)
func main() {
// Wrapping the unbuffered os.Stdin with a buffered scanner gives us a convenient
// Scan method that advances the scanner to the next token;
// which is the next line in the default scanner.
scanner := bufio.NewScanner(os.Stdin)
for scanner.Scan() {
ucl := strings.ToUpper(scanner.Text())
// Write out the uppercased line.
fmt.Println(ucl)
}
if err := scanner.Err(); err != nil {
fmt.Fprintln(os.Stderr, "error:", err)
os.Exit(1)
}
}
// println is a simple yet powerful builtin function.
// It can print anything: strings, numbers, arrays, maps, structs.
println(1) // "1"
println('hi') // "hi"
println([1,2,3]) // "[1, 2, 3]"
// Printing structs coming soon
println(User{name:'Bob', age:20}) // "User{name:'Bob', age:20}"
// If you want to define a custom print value for your type, simply define a .str() string method.
// If you don't want to print a newline, use print() instead.
eprintln("hello error")