How do I check if the user has entered a null value in Go?

醉酒当歌 提交于 2020-01-30 08:20:07

问题


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

How do I check if the user has entered a null value and where do I put the code? Note - I've already tried checking the length = 0 and = " " but, they don't seem to be working.

Please suggest an alternative way for doing this. Thanks!


回答1:


bufio.Reader.ReadString() returns a string that also contains the delimeter, in this case the newline character \n.

If the user does not enter anything just presses the Enter key, the return value of ReadString() will be "\n", so you have to compare the result to "\n" to check for empty input:

reader := bufio.NewReader(os.Stdin)
fmt.Print("Enter text: ")
text, err := reader.ReadString('\n')
if err != nil {
    panic(err) // Don't forget to check and handle returned errors!
}

if text == "\n" {
    fmt.Println("No input!")
} else {
    fmt.Println("Hello", text)
}

An even better alternative would be to use strings.TrimSpace() which removes leading and trailing white space characters (newline included; it isn't a meaningful name if someone inputs 2 spaces and presses Enter, this solution also filters that out). You can compare to the empty string "" if you called strings.TrimSpace() prior:

text = strings.TrimSpace(text)
if text == "" {
    fmt.Println("No input!")
} else {
    fmt.Println("Hello", text)
}


来源:https://stackoverflow.com/questions/43490148/how-do-i-check-if-the-user-has-entered-a-null-value-in-go

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!