在结构中使用地图的更好方法?去编程语言练习1.4

时间:2017-03-06 19:08:39

标签: go struct

我正在使用The Go Programming Language练习1.4。程序读取作为参数给出的标准输入或文件,并输出具有重复项的行。

我有工作代码,我只是想知道是否有更好的方法在结构中使用地图?现在,当找到唯一的行时,我在结构中创建了一个新的地图。但它看起来很笨拙,我想知道我是否应该采取另一种方式。

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: %v\n", 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
        }
}

我在countLines中使用tmp变量来解决无法直接分配到地图as outlined in the Go Github repo中的值的问题。

1 个答案:

答案 0 :(得分:0)

我不认为它特别凌乱,但我可能会想要制作某种addDupe辅助函数,该函数需要dupCount个值,无需进行任何更改即可添加并按行返回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