How to do it...

These steps cover writing and running your application:

  1. From your Terminal or console application, create a new directory called ~/projects/go-programming-cookbook/chapter2/pipes.
  2. Navigate to this directory.
  3. 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   
  1. Copy tests from ~/projects/go-programming-cookbook-original/chapter2/pipes, or use this as an opportunity to write some of your own code!
  2. 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)
}
}
  1. Run echo "some string" | go run pipes.go.
  2. 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
  1. If you copied or wrote your own tests, go up one directory and run go test. Ensure that all the tests pass.
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.144.98.13