Printing and format verbs
The three printing functions, and the verbs you will use every day.
Topic 3 of 98 · 5 min to read · 45 min to build
After this topic you can
- Choose between
Print,Println,PrintfandSprintffor a given output. - Predict the output of
Printfwith%v,%T,%q,%.2fand%5d. - Write a literal percent sign and a padded column with format verbs.
The three printing functions
output.go
name, age := "Sahdev", 25fmt.Print("no newline, no spaces between strings")fmt.Println("adds spaces and a newline:", name, age)fmt.Printf("formatted: %s is %d\n", name, age) // Printf needs its own \ns := fmt.Sprintf("%s is %d", name, age) // returns the string instead of printing itfmt.Println(s)Formatting verbs
| Verb | What it prints | Example output |
|---|---|---|
%v | the value in its default form — your default choice | 25 |
%T | the type of the value | int |
%d | an integer | 25 |
%s | a string | Sahdev |
%q | a quoted string — shows whitespace clearly | "Sahdev" |
%f / %.2f | a float / to two decimal places | 3.140000 / 3.14 |
%t | a bool | true |
%x | hexadecimal | 1f |
%5d / %-5s | pad to 5 wide, right / left aligned | 25 / ab |
%% | a literal percent sign | % |
Verbs you will meet later
%+vand%#vprint a struct with its field names. A struct is a value made of several named fields; you will learn it properly in Structs.%pprints a memory address. You will learn this in Pointers.%wwraps one error inside another, and only works infmt.Errorf. You will learn this in Error values.fmt.Fprintlnprints to a place you choose, such as the error streamos.Stderr, instead of the screen. It comes up in Interfaces.
Try it yourself
press Run — this executes on the Go Playground
package mainimport "fmt"func main() { name, age, height, student := "sahdev", 25, 1.72, true fmt.Printf("%v %v %v %v\n", name, age, height, student) // %v works for anything fmt.Printf("%T %T %T %T\n", name, age, height, student) // the types fmt.Printf("%s is %d years old and %.2f m tall\n", name, age, height) fmt.Printf("student? %t (%.1f%% done)\n", student, 62.5) fmt.Printf("%q vs %s\n", " spaces ", " spaces ") fmt.Printf("[%5d] [%-6s]\n", age, name)}The short version
Printlnfor quick output,Printffor formatted,Sprintfto build a string.%vis the default for any value,%Tshows the type.Printfneeds its own\n;Printlnadds one for you.- The
Sprefix (Sprintf,Sprintln) returns a string instead of printing it.
Remember:
%v prints anything and %T tells you its type. Learn them before you learn a debugger.Build this before moving on
Print a string, an int, a float and a bool with %v and then with %T, and compare the outputs.Then try these in your own editor
- 1Build a sentence with
Sprintf, store it in a variable, then print it withPrintln. - 2Format a float to two decimal places, and print a literal percent sign.
- 3Print a string with
%sand%qand see which one shows the whitespace.
Official documentation