go · level 2 · unit 3 · lesson 3
- meet it
- guess first
- your turn
- fix it
- nailed it
Tap a green word if you get lost.
meet it
An is anywhere that text can go.
io.Writer is an interface from the io toolbox. Anything with the right Write method satisfies it: the screen, a file, a reply to a web browser. You rarely call Write yourself, because fmt does it for you.
works like Println, but writes to w, any writer you choose. fmt.Fprintf does the same for Printf. os.Stdout is the screen, so fmt.Fprintln(os.Stdout, "Hi") prints as usual.
A is a writer that collects text instead of showing it. Its Write method has a pointer receiver, so hand over its address: fmt.Fprintf(&b, ...). Then b.String() gives back everything written.
package main
import "fmt"
import "io"
import "os"
import "strings"
func receipt(w io.Writer, item string, price int) {
fmt.Fprintf(w, "%v: £%v\n", item, price)
}
func main() {
receipt(os.Stdout, "tea", 2)
var b strings.Builder
receipt(&b, "cake", 3)
receipt(&b, "toast", 1)
fmt.Print("Saved for later:\n", b.String())
} Later you will hand a writer to a web server, and the same fmt.Fprintf will write the reply.
guess first
Screen or builder? Guess the order.
Guess before you run it. Wrong guesses are how you learn, and nothing is marked.
package main
import "fmt"
import "strings"
func main() {
var b strings.Builder
fmt.Fprintln(&b, "first")
fmt.Println("second")
fmt.Fprintln(&b, "third")
fmt.Print(b.String())
}
your turn
Your turn. Paint two signs.
Send your first sign to the screen with os.Stdout, and your second into the builder with &b. Type any message you like on each sign.
output
press run to see what happens
fix it
Go will not write the shopping list. Fix it!
output
press run to see what happens
- Read the whole error. It mentions that the
Writemethod has a pointer receiver. - With a pointer receiver, only a pointer to the builder counts as a writer.
- Change notes to ¬es inside fmt.Fprintln on line 6, then run.
nailed it
your words can go anywhere. :D
- An
io.Writeris anything that text can be written to. fmt.Fprintlnandfmt.Fprintfwrite to the writer you choose.- Hand a
strings.Builderover with&, then read it withString.
new words in your collection
- io.Writer
- Fprintln
- strings.Builder
This lesson isn’t saved. A free account remembers every lesson you finish.