Why I use:
var n int
a, _ := fmt.Scanf("%d",&n)
Then a == 1
, n
has changed its value by input.
Why I use:
var n int
a, _ := fmt.Scanf("%d",&n)
Then a == 1
, n
has changed its value by input.
fmt.Scanf()
returns the number of successfully scanned items:
Scanf scans text read from standard input, storing successive space-separated values into successive arguments as determined by the format. It returns the number of items successfully scanned. If that is less than the number of arguments, err will report why.
So if your input is a valid integer number fitting into an int
, fmt.Scanf()
will succeed to parse it and store it in n
, and so it will return 1.
Should you input an invalid number (e.g. the string
value "a"
), scanning would not succeed, so 0
would be returned along with a non-nil
error, like in this example:
var n int
a, err := fmt.Sscanf("a", "%d", &n)
fmt.Println(a, err)
Which outputs (try it on the Go Playground):
0 expected integer