如何在Golang中检查Scanln是否引发错误

huangapple go评论81阅读模式
英文:

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.

huangapple
  • 本文由 发表于 2015年3月17日 18:36:51
  • 转载请务必保留本文链接:https://go.coder-hub.com/29096916.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定