Skip to content

Instantly share code, notes, and snippets.

@synaptic-cleft
Created December 17, 2021 20:04
Show Gist options
  • Save synaptic-cleft/9f8a439ca4902bdfb246c70f3f2e7bc5 to your computer and use it in GitHub Desktop.
Save synaptic-cleft/9f8a439ca4902bdfb246c70f3f2e7bc5 to your computer and use it in GitHub Desktop.
Word count in Go
package main
import (
"fmt"
"os"
"bufio"
"strings"
)
func main() {
file, error := os.Open("/path/to/file")
if error != nil {
fmt.Println("Could not read file.")
os.Exit(1)
}
defer file.Close()
scanner := bufio.NewScanner(file)
words := 0
for scanner.Scan() {
line := strings.Fields(scanner.Text())
words += len(line)
}
fmt.Printf("File currently contains %d words.\n", words)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment