这个转换语句出了什么问题?

时间:2015-07-16 20:41:55

标签: go

有人能看出为什么这个开关无法工作吗?

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")
    }
}   

在此语句中,当对开关表达式进行硬编码时,始终返回默认值,切换块按预期工作。查看ReadString()函数代码,它返回一个字符串,所以我看不出任何理由让我的例子不起作用。

我做错了什么?!

4 个答案:

答案 0 :(得分:3)

根据docs

  

ReadString读取直到输入中第一次出现delim,返回包含的数据的字符串,并包括分隔符。

因此,您可以执行以下操作:

reader := bufio.NewReader(os.Stdin)
delim := byte('\n')
text, _ := reader.ReadString(delim)

switch text = strings.TrimRight(text, string(delim)); text {
  // ...
}

答案 1 :(得分:2)

text包含“\ n”,您需要匹配或修剪。

switch text = strings.TrimSpace(text); text {
case "a":
    fmt.Println("A")
case "b":
    fmt.Println("B")
case "c":
    fmt.Println("C")
default:
    fmt.Println("DEFAULT: " + text)
}

答案 2 :(得分:1)

您的文字由两个字节组成:fmt.Print(len(text))为2,fmt.Print(len("a"))为1。

您的第二个符号是不可见的,您可以尝试使用text = strings.TrimSpace(text)将其删除。

答案 3 :(得分:0)

因为 \n 文本有空格。您必须通过 strings.Trimspace() 方法将其删除。

包主

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

func main() {

    reader := bufio.NewReader(os.Stdin)
    text, _ := reader.ReadString('\n')
    fmt.Print(text)
    
    switch strings.TrimSpace(text) {
    case "a":
        fmt.Print("A\n")
    case "b":
        fmt.Print("B\n")
    case "c":
        fmt.Print("C\n")
    default:
        fmt.Print("DEFAULT\n")
    }
}  
相关问题