英文:
How to check if Scanln throws an error in Golang
问题
我是你的中文翻译助手,以下是翻译好的内容:
我刚开始学习Go语言。我一直在寻找答案,我知道答案肯定存在,只是我还没有找到。
为了更好地解释我的问题,这是我的代码:
func main() {
...
inputs := new(Inputs)
fmt.Println("Input two numbers: ")
fmt.Scanln(&inputs.A)
fmt.Scanln(&inputs.B)
fmt.Println("Sum is:", inputs.A + inputs.B)
}
这是我的结构体:
type Inputs struct {
A, B int
}
如果我将输入'123'作为输入A,并将另一个'123'作为输入B,我将得到输出"Sum is: 246"。但是,如果我错误地输入'123j',它将不再工作,因为A和B只接受整数。
现在,如何捕获fmt.Scanln的panic,或者是否有其他方法可以解决这个问题?提前感谢。
英文:
I am new to Go. I've been searching for answers and I know there really is one I just haven't found it.
To better explain my question, here is my code:
func main() {
...
inputs := new(Inputs)
fmt.Println("Input two numbers: ")
fmt.Scanln(&inputs.A)
fmt.Scanln(&inputs.B)
fmt.Println("Sum is:", inputs.A + inputs.B)
}
And here is my struct:
type Inputs struct {
A, B int
}
If I will input '123' for Input A and another '123' for Input B, I will have an output of "Sum is: 246". But if I will mistakenly input '123j' , it will no longer work since A and B accept int(s) only.
Now, how to catch the panic from fmt.Scanln or is there a way? Thanks in advance.
答案1
得分: 7
Scanln返回值 ... 不要忽略它们。
你正在忽略两个重要的返回值。扫描的计数和一个错误...如果有的话。
n, err := fmt.Scanln(&inputs.A)
...将给你需要检查的内容。err
会告诉你期望一个换行符但没有找到...因为你尝试将值存储在一个int
中...当可用值的最后一个字符不是换行符时,会引发错误。
英文:
Scanln returns values ... don't ignore them.
You're ignoring two important return values. The count of the scan and an error .. if there was one.
n, err := fmt.Scanln(&inputs.A)
...will give you what you need to check. err
will tell you that a newline was expected and wasn't found .. because you've tried to store the value in an int
.. and it errors when the last character in the available value isn't a newline.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论