These steps cover writing and running your application:
- From your Terminal or console application, create a new directory called ~/projects/go-programming-cookbook/chapter2/pipes.
- Navigate to this directory.
- Run the following command:
$ go mod init github.com/PacktPublishing/Go-Programming-Cookbook-Second-Edition/chapter2/pipes
You should see a file called go.mod that contains the following:
module github.com/PacktPublishing/Go-Programming-Cookbook-Second-Edition/chapter2/pipes
- Copy tests from ~/projects/go-programming-cookbook-original/chapter2/pipes, or use this as an opportunity 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 ")
for key, value := range WordCount(os.Stdin) {
fmt.Printf("%s: %d ", key, value)
}
}
- Run echo "some string" | go run pipes.go.
- You may also run the following commands:
$ 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 that all the tests pass.