DEV Community

Cover image for Printing formatted things in Go with Printf()
Onelinerhub
Onelinerhub

Posted on

Printing formatted things in Go with Printf()

Go allows formatting things and printing them using Printf() function (as well as most of other languages). The function is a part of fmt package and works exactly the same as in all other langs:

package main
import "fmt"

func main() {
  fmt.Printf("%d", 123) // 123
}
Enter fullscreen mode Exit fullscreen mode

Here we've printed 123 value as number (%d).

Printing padded numbers

Sometimes you might want to pad numbers with zeros:

fmt.Printf("%05d", 123) // 00123
Enter fullscreen mode Exit fullscreen mode

Which will give 00123 (left pad given number to 5 symbols and using zeros to fill).

Printing booleans

For boolean variables %t format can be used to get text representation:

fmt.Printf("%t", true) // true
fmt.Printf("%t", false) // false
Enter fullscreen mode Exit fullscreen mode

Sprintf() works like Printf(), but returns a string instead of printing it.

Good tutorial and cheat-sheet on possible format options.

Top comments (0)