How to fix multiple value for single value context error in Golang?

Viewed 7167
package main
import "fmt"

func main() {
    fmt.Println("Enter a number: ")
    var addendOne int = fmt.Scan()
    fmt.Println("Enter another number: ")
    var addendTwo int = fmt.Scan()
    sum := addendOne + addendTwo
    fmt.Println(addendOne, " + ", addendTwo, " = ", sum)
}

This raises an error:

multiple values in single-value context.

Why does it happen and how do we fix it?

3 Answers

fmt.Scan returns two values, and you're only catching one into addedOne. you should catch the error as well like this:

addendTwo, err := fmt.Scan() 
if err != nil {
  // handle error here
}

if you want to ignore the error value (not recommended!), do it like this:

addendTwo, _ := fmt.Scan() 

fmt.Scan() returns two values and your code expects just one when you call it.

The Scan signature func Scan(a ...interface{}) (n int, err error) returns first the number of scanned items and eventually an error. A nil value in the error position indicates that there was no error.

Change your code like this:

addendOne, err := fmt.Scan()
if err != nil {
    //Check your error here
}

fmt.Println("Enter another number: ")
addendTwo, err := fmt.Scan()
if err != nil {
    //Check your error here
}

If you really want to ignore the errors you can used the blank identifier _:

addendOne, _ := fmt.Scan()

Because Scan returns int and error so you should use the := syntax that is shorthand for declaring and initializing.

addendOne, err := fmt.Scan()
addendTwo, err := fmt.Scan()

From golang fmt documentation:

func Scan(a ...interface{}) (n int, err error)

Related