Skip to content

Go Formatting Verbs

In Go, "formatting verbs" are special placeholders used with functions like fmt.Printf to control how values are displayed.

Common Verbs

Verb Usage Example Output
%v Default format (works for almost anything) {val: 123}
%+v Struct with field names {Name: "John"}
%T The Type of the value int, string
%d Decimal integer 15
%b Binary integer 1111
%f Float (decimal) 1.234567
%.2f Float with 2 decimal places 1.23
%s Basic string hello
%q Quoted string "hello"
%p Pointer (memory address) 0xc000...

Basic Example

package main

import "fmt"

type point struct {
    x, y int
}

func main() {
    p := point{1, 2}

    // %v is the safest bet for any value
    fmt.Printf("Default: %v\n", p)   // {1 2}
    fmt.Printf("Fields:  %+v\n", p)  // {x:1 y:2}
    fmt.Printf("Type:    %T\n", p)   // main.point

    // Numbers and Strings
    fmt.Printf("Binary: %b\n", 15)      // 1111
    fmt.Printf("Float:  %.2f\n", 3.1415) // 3.14
    fmt.Printf("Quoted: %q\n", "cafe")   // "cafe"
}

Width and Padding

You can also control the spacing of your output:

  • %5d: Puts at least 5 spaces of width, right-justified.
  • %-5d: Puts at least 5 spaces of width, left-justified.
  • %05d: Pads with zeros (e.g., 00042).
fmt.Printf("|%5d|%5d|\n", 1, 2)   // |    1|    2|
fmt.Printf("|%-5d|%-5d|\n", 1, 2) // |1    |2    |