4
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?

Rene Knop
  • 1,788
  • 3
  • 15
  • 27
Aryamaan Goswamy
  • 319
  • 1
  • 2
  • 16
  • Possible duplicate of [multiple-value strconv.ParseInt() in single-value context](https://stackoverflow.com/questions/47138003/multiple-value-strconv-parseint-in-single-value-context) – Adrian Nov 06 '18 at 15:20
  • There are dozens of questions on SO about "multiple values in single-value context" errors, all of which have basically the same answers. Please take a quick search of SO and see if you can find your answer. – Adrian Nov 06 '18 at 15:21
  • @Adrian I am only a beginner at Golang and I can't understand any of the code in the first place. – Aryamaan Goswamy Nov 06 '18 at 17:20
  • 2
    Consider taking the [Tour of Go](https://tour.golang.org/welcome/1) which does an excellent job of explaining the basic concepts and syntax of the language. – Adrian Nov 06 '18 at 17:26

3 Answers3

7

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() 
AnatPort
  • 748
  • 8
  • 20
2

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()
Guillaume Barré
  • 4,168
  • 2
  • 27
  • 50
0

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)

Mr.Teapot
  • 141
  • 2
  • 6