为了账号安全,请及时绑定邮箱和手机立即绑定

Golang os.stdin 作为 Goroutines 中的读者

Golang os.stdin 作为 Goroutines 中的读者

Go
小唯快跑啊 2021-11-22 17:43:54
在 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)    }}()

1 回答

?
莫回无

TA贡献1865条经验 获得超7个赞

是的,这完全没问题。只要这是与 交互的唯一 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)

    }

}()


查看完整回答
反对 回复 2021-11-22

添加回答

代码语言

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号