Home > Enterprise >  Why is the answer correct when using Scanf unsafe, but not when handling errors? (Go)
Why is the answer correct when using Scanf unsafe, but not when handling errors? (Go)

Time:07-17

Just recently I started to learn Go. I did a simple task for JetBrains Academy. There is a very simple code:

    var number int
    fmt.Scanf("%d", &number)

    if number > 0 {
        fmt.Println("Positive!")
    } else if number < 0 {
        fmt.Println("Negative!")
    } else {
        fmt.Println("Zero!")

This code works just fine, but if I use the auto-generated error handling from the IDE:

    var number int
    number, err := fmt.Scanf("%d", &number)
    if err != nil {
        return
    }

    if number > 0 {
        fmt.Println("Positive!")
    } else if number < 0 {
        fmt.Println("Negative!")
    } else {
        fmt.Println("Zero!")
    }

If you enter a number "0", the output will be "Positive!", not "Zero!" Why is that?

CodePudding user response:

   number, err := fmt.Scanf("%d", &number)

This will first store the parsed value into number inside the call of Scanf. Then Scanf will return and your code will store 1 into number, since this is the number of items successfully scanned (see the documentation what Scanf returns).

To fix you should not use the same variable both for storing the parsed result and for storing the return value of Scanf. Also it helps a lot to name the variables precisely according to their intended use in order to avoid confusion when writing and debugging the code, i.e.

parsedItems, err := fmt.Scanf("%d", &number)

 
  • Related