Reading Input
You have already seen fmt.Scan in some exercises. It reads values from the input and stores them in variables. This lesson shows how it works.
This program reads a name and an age. Here it gets the input Bob on the first line and 45 on the second:
package main
import "fmt"
func main() {
var name string
var age int
fmt.Scan(&name, &age)
fmt.Println("Hi", name, "you are", age)
}
Output:
Hi Bob you are 45
fmt.Scan reads the text 45 and turns it into the number 45, because age is an int. It always converts the input to the type of the variable.
Why the & ?
fmt.Scan must put a value into your variable, so it needs to know where that variable is in memory. &age means "the place where age is stored". The Pointers lesson explains this fully. For now, remember to put & in front of every variable you give to fmt.Scan.
If you forget it, the program still compiles, but fmt.Scan cannot fill the variable. With the input 30:
var age int
fmt.Scan(age)
fmt.Println("age:", age)
Output:
age: 0
age kept its zero value, and there was no message. When a value you read is always 0, check for a missing & first.
Spaces and new lines
fmt.Scan splits the input at spaces and at new lines, and it treats both the same. With the input 10 20 on one line, this prints the sum:
var a, b int
fmt.Scan(&a, &b)
fmt.Println(a + b)
Output:
30
The input 10 and 20 on two lines gives the same result. This also means that one string variable gets only one word. Here is the first program again, with the input Mary Ann 30:
var name string
var age int
fmt.Scan(&name, &age)
fmt.Println("Hi", name, "you are", age)
Output:
Hi Mary you are 0
name got only Mary. Then fmt.Scan tried to read Ann as a number, failed, and stopped. age stayed 0.
Finding bad input
fmt.Scan gives back two values: how many values it read, and an error. If the input abc arrives where a number is expected:
var age int
n, err := fmt.Scan(&age)
fmt.Println(n, err)
fmt.Println("age:", age)
Output:
0 expected integer
age: 0
fmt.Scan read 0 values, and the error says what it wanted. With good input, the error is <nil>, which means "no error". The Returning Errors lesson shows how to check an error and react to it. The exercises in this course always give correct input, so they do not check the error.
fmt.Scan reads one word or one number at a time, and that is all this course needs. To read a whole line with its spaces, Go has another package, bufio, which you can learn after this course.
In the exercise, fill in the fmt.Scan call so it reads an order ID and a customer name.