package main
import (
"fmt"
"io"
"strings"
)
// Define interfaces where they\'re USED, not where they\'re implemented.
// This function works with anything that can be read from.
func WordCount(r io.Reader) (int, error) {
buf := make([]byte, 1024)
count, total := 0, 0
for {
n, err := r.Read(buf)
for _, b := range buf[:n] {
if b == ' ' || b == '\n' { count++ }
}
total += n
if err == io.EOF { break }
if err != nil { return 0, err }
}
return count + 1, nil // last word
}
func main() {
// Pass anything that implements io.Reader
n, _ := WordCount(strings.NewReader("hello world foo bar"))
fmt.Println("words:", n) // 4
// Could also be a file, network connection, gzip stream, etc.
}
Create a free account and build your private vault. Share publicly whenever you want.