LESSON · 1 OF 33

Printf and the format string

Printf and the format string

You have already used fmt.Println. It prints its arguments with a space between each one and a newline at the end, and gives you no control over the layout:

go
fmt.Println("port:", 8080)   // port: 8080

fmt.Printf is the one to reach for when you want the output laid out exactly. It takes a format string with placeholders, called verbs, and fills them in from the arguments that follow:

go
fmt.Printf("port: %d\n", 8080)   // port: 8080

The %d is a verb that means "put an integer here". One difference to remember: Printf does not add a newline for you, so you write the \n yourself at the end of the format string.

When the exact shape of a line matters, Printf is the tool.

Spin up a fresh environment and practice live.
go · fresh machine · ready in under a minute