Below is the main.go file to with a function to count words:
package main
import (
"bufio"
"fmt"
"io"
"os"
)
func count(r io.Reader) int {
// A scanner is used to read text from a Reader (such as files)
scanner := bufio.NewScanner(r)
// Define the scanner split type to words (default is split by lines)
scanner.Split(bufio.ScanWords)
// Defining a counter
wc := 0
// For every word scanned, increment the counter
for scanner.Scan() {
wc++
}
// Return the total
return wc
}
func main() {
// Calling count function to count the number of words
// received from the Standard Input and printing it out
fmt.Println(count(os.Stdin))
}
Here is a test (main_test.go) for the count function:
package main
import (
"bytes"
"testing"
)
// TestCountWords tests the count function set to count words
func TestCountWords(t *testing.T) {
b := bytes.NewBufferString("word1 word2 word3 word4\n")
exp := 4
res := count(b)
if res != exp {
t.Errorf("Expected %d, got %d instead. \n", exp, res)
}
}
When executed, the counter looks like this:
❯ echo "I like programming in Go" | ./wc
5
While the test looks like this:
❯ ls
go.mod main.go main_test.go wc
❯ go test -v
=== RUN TestCountWords
--- PASS: TestCountWords (0.00s)
PASS
ok wc 0.173s