go · level 1 · unit 3 · lesson 4
- meet it
- guess first
- your turn
- fix it
- nailed it
Tap a green word if you get lost.
meet it
fills in the gaps in a sentence.
fmt.Printf fills in a sentence for you. Write the text with %v wherever a value should go, then list the values after commas. Each %v is a , and they are filled in order.
Printf does not move to a new line on its own, so end the text with \n, which means new line. works the same way but hands the text back, ready to store in a box.
To join a number onto a string with +, turn it into text first. The toolbox does that: strconv.Itoa(10) hands back "10".
package main
import "fmt"
import "strconv"
func main() {
name := "Ava"
score := 42
fmt.Printf("%v scored %v points\n", name, score)
label := fmt.Sprintf("Player: %v", name)
fmt.Println(label)
fmt.Println("Score: " + strconv.Itoa(score))
} Itoa is short for "integer to ASCII", an old way of saying number to text.
guess first
The values go in order. What will this show?
Guess before you run it. Wrong guesses are how you learn, and nothing is marked.
package main
import "fmt"
func main() {
fmt.Printf("%v has %v cats\n", 3, "Leo")
}
your turn
Your turn. How hungry are you?
Type a food between the quotes and a whole number after count :=. Then press run to see Printf fill the gaps.
output
press run to see what happens
fix it
Go will not join this number. Can you fix it?
output
press run to see what happens
- Read the error. Go cannot use
+with a string and aninttogether. - Let
Printfslot the number into the sentence with a%vplaceholder instead. - Change line 5 to fmt.Printf("You reached level %v\n", level), then press run.
nailed it
you slotted values into sentences. :D
Printffills each%vplaceholder with a value, in order.- End
Printftext with\nto start a new line. strconv.Itoaturns a number into text.
new words in your collection
- Printf
- placeholder
- Sprintf
- strconv
This lesson isn’t saved. A free account remembers every lesson you finish.