有人能看出为什么这个开关不起作用吗?
func main() {
reader := bufio.NewReader(os.Stdin)
text, _ := reader.ReadString('\n')
fmt.Print(text)
switch text {
case "a":
fmt.Print("A\n")
case "b":
fmt.Print("B\n")
case "c":
fmt.Print("C\n")
default:
fmt.Print("DEFAULT\n")
}
}
在此语句中,始终返回默认值,但在对 switch 表达式进行硬编码时,switch block 会正常工作。查看 ReadString() 函数代码,它返回一个字符串,所以我看不出有任何理由导致我的示例不起作用。
我做错了什么吗?!
最佳答案
根据 docs :
ReadString reads until the first occurrence of delim in the input, returning a string containing the data up to and including the delimiter.
因此你可以这样做:
reader := bufio.NewReader(os.Stdin)
delim := byte('\n')
text, _ := reader.ReadString(delim)
switch text = strings.TrimRight(text, string(delim)); text {
// ...
}
关于go - 这个 go switch 语句有什么问题?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31464142/