我有一个精心设计的程序,目标是在stdin上 echo 文本(您想要的次数),并在10秒后退出.代码如下:
package main
import (
"bufio"
"fmt"
"os"
"time"
)
func main() {
input := make(chan string)
abort := make(chan bool)
// exit after 10 sec
go func() {
time.Sleep(10 * time.Second)
abort <- true
}()
go func() {
cmd := bufio.NewScanner(os.Stdin)
for cmd.Scan() {
input <- "<- " + cmd.Text()
}
}()
select {
case <-abort:
fmt.Println("exiting")
return
case cmd := <-input:
fmt.Println(cmd)
}
}
问题是,当我输入第一行文本时,它被 echo 到标准输出,程序退出.我想在10秒内输入任意数量的命令.
我做错了什么?