go · level 1 · unit 2 · lesson 4
- meet it
- guess first
- your turn
- fix it
- nailed it
Tap a green word if you get lost.
meet it
waits for an answer and stores it.
Programs get more fun when they listen. Ask a question with , which works like Println but stays on the same line. Then fmt.Scan waits for the person to type and press Enter. What they type is .
Scan needs a box to put the answer in. Make an empty one first with name := "", then write fmt.Scan(&name). The & hands Scan the box itself, so it can put the answer inside.
Scan reads one word at a time. If someone types two words, the second one waits for the next Scan.
package main
import "fmt"
func main() {
name := ""
fmt.Print("What is your name? ")
fmt.Scan(&name)
fmt.Println("Hello,", name)
} What the person types is not part of the output, so the reply appears right after the question.
guess first
Someone types crisps. What appears?
Guess before you run it. Wrong guesses are how you learn, and nothing is marked.
package main
import "fmt"
func main() {
snack := ""
fmt.Print("Favourite snack? ")
fmt.Scan(&snack)
fmt.Println("Yum,", snack)
}
your turn
Your turn. Write the second question.
Write a question asking for a favourite food in the blank. End it with a space. We will answer Sam and pancakes.
output
press run to see what happens
fix it
The answer went missing. Can you fix it?
output
press run to see what happens
- The question appears, but the answer never shows. Look at the Scan line.
- Scan can only put the answer in if you hand it the box itself.
- Put & in front of food inside Scan's brackets: fmt.Scan(&food). Then press run.
nailed it
your program can listen now. :D
fmt.Printasks a question and stays on the same line.fmt.Scan(&box)waits for an answer and puts it in the box.- Scan reads one word at a time.
new words in your collection
- input
- Scan
This lesson isn’t saved. A free account remembers every lesson you finish.