If statement 如何在golang中编写干燥有效的if语句?
我有以下代码:If statement 如何在golang中编写干燥有效的if语句?,if-statement,go,If Statement,Go,我有以下代码: func main() { // counts := make(map[string]int) files := os.Args[1:] if len(files) == 0 { counts := make(map[string]int) countLines(os.Stdin, counts) fmt.Println("os.Stdin") printCounts(counts)
func main() {
// counts := make(map[string]int)
files := os.Args[1:]
if len(files) == 0 {
counts := make(map[string]int)
countLines(os.Stdin, counts)
fmt.Println("os.Stdin")
printCounts(counts)
} else {
for _, arg := range files {
counts := make(map[string]int)
f, err := os.Open(arg)
if err != nil {
fmt.Fprintf(os.Stderr, "dup2: %v\n", err)
continue
}
countLines(f, counts)
f.Close()
// print counts of each file
printCounts(counts)
}
}
}
func printCounts(counts map[string]int) {
//...
}
func countLines(f *os.File, counts map[string]int){
//...
}
在if-else语句中,我重复了自己两次启动counts dict,
(counts:=make(map[string]int)
)在if和else中
我的问题是,地鼠写这篇文章的方式是什么
使用
new
在if-else station之外进行分配并在每个块中进行初始化是否更好?我看不到您的代码中有太多重复。你可以以某种方式将if和else部分合并,但我不喜欢
一个简单的重构就是将counts
初始化移动到countLines
函数中,并使其返回
func countLines(f *os.File, counts map[string]int)
->
在做大量工作(比如说至少10万次分配)之前,不要过多考虑分配问题,在进行少量优化之前,先分析一下代码。映射不仅会在
make
上分配内存,还会在附加到映射时分配内存,并且它们的哈希表已满。为什么不简单地将if/else的主体提取到它们自己的函数中呢?这与个人意见有关,没有最好的方法。但是Sergio是正确的,只要有一个组合的countLines
和printCounts
函数,它只接受一个文件。谢谢,我试过了,它确实是一个紧凑的代码。
func countLines(f *os.File) map[string]int