我正在从GO编程语言中进行练习1.4。该程序读取stdin或作为参数和输出线的stdin或文件。
我有工作代码,我只是想知道是否有更好的方法在结构内使用地图?目前,当发现独特的线路时,我在结构中制作了一个新地图。但这似乎很笨拙,我想知道我是否应该以这种方式接触。
type dupCount struct {
count int
fileCount map[string]int
}
func main() {
counts := make(map[string]dupCount)
files := os.Args[1:]
if len(files) == 0 {
countLines(os.Stdin, counts, "stdin")
} else {
for _, arg := range files {
f, err := os.Open(arg)
if err != nil {
fmt.Fprintf(os.Stderr, "dup2: %vn", err)
continue
}
countLines(f, counts, arg)
f.Close()
}
}
func countLines(f *os.File, counts map[string]dupCount, filename string) {
input := bufio.NewScanner(f)
for input.Scan() {
var tmp = counts[input.Text()]
if tmp.count == 0 {
tmp.fileCount = make(map[string]int)
}
tmp.count++
tmp.fileCount[filename]++
counts[input.Text()] = tmp
}
}
我正在使用countline中的TMP变量来绕开Go Github repo中概述的地图中的值直接分配。
我认为这不是特别凌乱,但是我可能很想制作某种 addDupe
助手函数,该功能逐个值 dupCount
,使添加行所需的任何更改都需要通过Value返回dupCount
func addDupe(dupes dupCount, filename string) dupCount {
if dupes.count == 0 {
dupes.fileCount = make(map[string]int)
}
dupes.fileCount[filename]++
dupes.count++
return dupes
}
这类似于切片的标准append
功能的工作方式。那么countLines
可以写为:
func countLines(r io.Reader, counts map[string]dupCount, filename string) {
input := bufio.NewScanner(r)
for input.Scan() {
line := input.Text()
counts[line] = addDupe(counts[line], filename)
}
}
,但我所做的就是用函数参数替换您的tmp
。