我是 golang 的新手,我不明白为什么我不能让下一个代码工作:
func ListApps(){
fmt.Printf("\nPress Q to go back..\n")
reader := bufio.NewReader(os.Stdin)
input, _ := reader.ReadString('\n')
if string(input) == "q" {
fmt.Printf("OK")
}
}
我想打印一条消息,然后在控制台中扫描用户的输入,比较输入并在输入等于字符串“q”时打印 messsafe。由于某些原因,上次检查无效。
最佳答案
来自 TFM:
ReadString reads until the first occurrence of delim in the input, returning a string containing the data up to and including the delimiter
您正在比较没有分隔符的字符串。
就这样:
if input == "q\n" {...}
会起作用(顺便说一句,不需要调用 string(input)
,因为输入已经是一个字符串)。
或者,您也可以在检查之前使用 strings.TrimRight
修剪端线。这将使代码更具可移植性,因为它可以在 \r\n
用于分隔行的 Windows 上运行。所以这样做:
input = strings.TrimRight(input, "\r\n")
if input == "q" {
fmt.Println("OK")
}
我已经测试过它可以自己工作。
关于Golang 不处理 2 个操作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36180836/