无法在 play.golang.org 获取输入

Cannot get input at play.golang.org

我尝试了以下方法:

https://play.golang.org/p/a7ZLY2mumnI

package main

import (
    "bufio"
    "fmt"
    "os"
)

func main() {
    reader := bufio.NewReader(os.Stdin)
    fmt.Print("Enter text: ")
    text, _ := reader.ReadString('\n')
    fmt.Println(text)
}

但是,程序在我输入任何内容之前就退出了。

有人知道我做错了什么吗?

Go playground 不支持交互式程序。它无法读取 os.Stdin.

详情见this issue

这在“关于”部分也有说明:

The playground can use most of the standard library, with some exceptions. The only communication a playground program has to the outside world is by writing to standard output and standard error.

由于某些原因,Go Playground 不允许输入标准输入。但是您可以使用一个快速技巧:

  1. 创建初始化函数
  2. 将您的输入写入文件
  3. 读取文件内容到os.Stdin

Go Playground