3

可以在 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)
    }
}()
4

1 回答 1

2

是的,这很好。只要这是唯一与 交互的 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)
    }
}()
于 2015-11-17T21:32:52.487 回答