
上QQ阅读APP看书,第一时间看更新
How to do it...
These steps cover writing and running your application:
- From your terminal/console application, create a new directory called chapter2/pipes and navigate to that directory.
- Copy tests from https://github.com/agtorre/go-cookbook/tree/master/chapter2/pipes, or use this as an exercise to write some of your own code!
- Create a file called pipes.go with the following contents:
package main
import (
"bufio"
"fmt"
"io"
"os"
)
// WordCount takes a file and returns a map
// with each word as a key and it's number of
// appearances as a value
func WordCount(f io.Reader) map[string]int {
result := make(map[string]int)
// make a scanner to work on the file
// io.Reader interface
scanner := bufio.NewScanner(f)
scanner.Split(bufio.ScanWords)
for scanner.Scan() {
result[scanner.Text()]++
}
if err := scanner.Err(); err != nil {
fmt.Fprintln(os.Stderr, "reading input:", err)
}
return result
}
func main() {
fmt.Printf("string: number_of_occurrences\n\n")
for key, value := range WordCount(os.Stdin) {
fmt.Printf("%s: %d\n", key, value)
}
}
- Run echo "some string" | go run pipes.go.
- You may also run these:
go build
echo "some string" | ./pipes
You should see the following output:
$ echo "test case" | go run pipes.go
string: number_of_occurrences
test: 1
case: 1
$ echo "test case test" | go run pipes.go
string: number_of_occurrences
test: 2
case: 1
- If you copied or wrote your own tests, go up one directory and run go test. Ensure all tests pass.