Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

go

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?

like image 928
Aryamaan Goswamy Avatar asked Sep 19 '25 18:09

Aryamaan Goswamy


2 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() 
like image 130
AnatPort Avatar answered Sep 22 '25 06:09

AnatPort


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()
like image 35
Guillaume Barré Avatar answered Sep 22 '25 06:09

Guillaume Barré