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?
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()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With