Golang os.stdin作为Goroutines中的阅读器

林尼罗德

在Goroutine中将os.stdin用作Reader可以吗?基本上,我要完成的工作是使用户能够在不阻塞主线程的情况下输入消息。

例子:

go func() {
    for {
        consolereader := bufio.NewReader(os.Stdin)

        input, err := consolereader.ReadString('\n') // this will prompt the user for input

        if err != nil {
             fmt.Println(err)
             os.Exit(1)
        }

        fmt.Println(input)
    }
}()
乔什夫

是的,这很好。只要这是唯一与之交互的goroutine os.Stdin,一切都将正常运行。

顺便说一句,您可能想使用bufio.Scanner-与它一起使用会更好bufio.Reader

go func() {
    consolescanner := bufio.NewScanner(os.Stdin)

    // by default, bufio.Scanner scans newline-separated lines
    for consolescanner.Scan() {
        input := consolescanner.Text()
        fmt.Println(input)
    }

    // check once at the end to see if any errors
    // were encountered (the Scan() method will
    // return false as soon as an error is encountered) 
    if err := consolescanner.Err(); err != nil {
         fmt.Println(err)
         os.Exit(1)
    }
}()

本文收集自互联网,转载请注明来源。

如有侵权,请联系[email protected] 删除。

编辑于
0

我来说两句

0条评论
登录后参与评论

相关文章