Search code examples
gopanic

How to check if Scanln throws an error in Golang


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.


Solution

  • 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.