I'm trying to move from Python to GO and with my minimal knowledge I tried to make a basic calculator. However i for some reason can't get Scanf to work properly. It only seems to accept the first scanf but the second one is completely ignored
package main
import (
"fmt"
)
var x int
var y int
var result int
var input float64
func add(x int, y int) int {
sum := x + y
return sum
}
func sub(x int, y int) int {
sum := x - y
return sum
}
func div(x int, y int) int {
sum := x / y
return sum
}
func mul(x int, y int) int {
sum := x * y
return sum
}
func main() {
fmt.Println("Which type?
1: Add
2: Subtract
3: Divide
4:
Multiply")
fmt.Scanf("%d", &input)
fmt.Println("Input numbers seperated by space")
fmt.Scanf("%d", x, y)
switch input {
case 1:
result = add(x, y)
case 2:
result = sub(x, y)
case 3:
result = div(x, y)
case 4:
result = mul(x, y)
}
fmt.Println(result)
}
The second call to Scanf, Scanf("%d", x, y)
only provides one conversion specifier but was given two variables.
Moreover, this second call only passes the variables' values, not their addresses.
It seems the correct call would be Scanf("%d %d", &x, &y)
In the first call to Scanf you said: Scanf("%d", &input)
. The second argument's syntax, & variable
, denotes a reference to the named variable.
input
was declared global, but is only visible after its declaration. Since input
is in scope within main
but not within Scanf
, in order for Scanf
to change the value in another scope, the address must be given as an argument, rather than its value.
The recipient of the address (here Scanf
) can then change the value of the variable in the frame in which it is still in scope; in this case, main
.
See Go's documentation for a similar explanation: https://golang.org/ref/spec#Address_operators