If statement reader.ReadString不会删除第一次出现的delim

If statement reader.ReadString不会删除第一次出现的delim,if-statement,go,If Statement,Go,我编写了一个简单的go程序,但它不能正常工作: package main import ( "bufio" "fmt" "os" ) func main() { reader := bufio.NewReader(os.Stdin) fmt.Print("Who are you? \n Enter your name: ") text, _ := reader.ReadString('\n') if aliceOrBob(text) {

我编写了一个简单的go程序,但它不能正常工作:

package main

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

func main() {
    reader := bufio.NewReader(os.Stdin)
    fmt.Print("Who are you? \n Enter your name: ")
    text, _ := reader.ReadString('\n')
    if aliceOrBob(text) {
        fmt.Printf("Hello, ", text)
    } else {
        fmt.Printf("You're not allowed in here! Get OUT!!")
    } 
}

func aliceOrBob(text string) bool {
    if text == "Alice" {
        return true
    } else if text == "Bob" {
        return true
    } else {
        return false
    }
}
它应该让用户说出它的名字,如果他是Alice或Bob,就向他打招呼,否则就告诉他离开。 问题是,即使输入的名字是Alice或Bob,它也会告诉用户退出

爱丽丝:

/usr/lib/golang/bin/go run /home/jcgruenhage/go/workspace/src/github.com/jcgruenhage/helloworld/greet/greet.go
Who are you? 
Enter your name: Alice
You're not allowed in here! Get OUT!!
Process finished with exit code 0
鲍勃:


我对Go一无所知,但您可能希望去掉字符串的前导或尾随空格以及其他空白字符(制表符、换行符等)。

这是因为您的
文本
正在存储
Bob\n

解决此问题的一种方法是使用
strings.TrimSpace
修剪换行符,例如:

import (
    ....
    "strings"
    ....
)

...
if aliceOrBob(strings.TrimSpace(text)) {
...
或者,您也可以使用
ReadLine
而不是
ReadString
,例如:

...
text, _, _ := reader.ReadLine()
if aliceOrBob(string(text)) {
...

之所以需要
string(text)
,是因为ReadLine将返回
byte[]
而不是
string

我认为这里的困惑源于:

text, _ := reader.ReadString('\n')
不删除
\n
,而是将其保留为最后一个值,并忽略它之后的所有内容

ReadString一直读取,直到输入中第一次出现delim, 返回一个字符串,该字符串包含在 定界符

然后比较
Alice
Alice\n
。因此,解决方案是在
aliceOrBob
函数中使用
Alice\n
,或者像@ch33hau所指出的那样,以不同的方式读取输入

reader.ReadLine() 

可以离开'\n',但reader.ReadString()不能

谢谢,没有想到^^你的答案令人困惑。请你重新格式化并加上额外的解释好吗?
reader.ReadLine()