go聖經裏有一段查找重複的行的代碼,發現輸入無反應不會打印重複行數據
// Dup1 prints the text of each line that appears more than
// once in the standard input, preceded by its count.
package main
import (
"bufio"
"fmt"
"os"
)
func main() {
counts := make(map[string]int)
input := bufio.NewScanner(os.Stdin)
for input.Scan() {
counts[input.Text()]++
}
if input.Err() != nil{
fmt.Print("err")
}
// NOTE: ignoring potential errors from input.Err()
for line, n := range counts {
if n > 1 {
fmt.Printf("%d\t%s\n", n, line)
}
}
}
其實是input.Scan() 這個循環裏面沒有跳出,程序會一直監聽輸入信息,只要加個中斷跳出就非常明白了:
// Dup1 prints the text of each line that appears more than
// once in the standard input, preceded by its count.
package main
import (
"bufio"
"fmt"
"os"
)
func main() {
counts := make(map[string]int)
input := bufio.NewScanner(os.Stdin)
for input.Scan() {
// 控制循環退出
if input.Text() == "end" { break }
counts[input.Text()]++
}
if input.Err() != nil{
fmt.Print("err")
}
// NOTE: ignoring potential errors from input.Err()
for line, n := range counts {
if n > 1 {
fmt.Printf("%d\t%s\n", n, line)
}
}
}
再次輸入
go run ch1/dup1/main.go
a
a
b
b
c
end
輸出
2 a
2 b