September 2017
Intermediate to advanced
466 pages
9h 33m
English
A very common programming problem is finding out the number of times an IP address appears in a log file. So, the example in this subsection will show you how to do this using a handy map structure. The occurrences.go program will be presented in three parts.
The first part is as follows:
package main
import (
"fmt"
"strings"
)
func main() {
var s [3]string
s[0] = "1 b 3 1 a a b"
s[1] = "11 a 1 1 1 1 a a"
s[2] = "-1 b 1 -4 a 1"
The second part is as follows:
counts := make(map[string]int)
for i := 0; i < len(s); i++ {
data := strings.Fields(s[i])
for _, word := range data {
_, ok := counts[word]
if ok {
counts[word] = counts[word] + 1
} else {
counts[word] = 1
}
}
}
Here, we use the knowledge from the ...
Read now
Unlock full access