Skip to main content
Go offers excellent support for string formatting in the printf tradition. Here are examples of common string formatting tasks.

Basic Formatting Verbs

Structs

type point struct {
    x, y int
}

p := point{1, 2}
fmt.Printf("struct1: %v\n", p)
// Output: struct1: {1 2}

fmt.Printf("struct2: %+v\n", p)
// Output: struct2: {x:1 y:2}

fmt.Printf("struct3: %#v\n", p)
// Output: struct3: main.point{x:1, y:2}
Prints the value in a default format
For structs, includes field names
Prints a Go syntax representation of the value

Types and Booleans

fmt.Printf("type: %T\n", p)
// Output: type: main.point

fmt.Printf("bool: %t\n", true)
// Output: bool: true

Integer Formatting

fmt.Printf("int: %d\n", 123)
// Output: int: 123

Float Formatting

fmt.Printf("float1: %f\n", 78.9)
// Output: float1: 78.900000

fmt.Printf("float2: %e\n", 123400000.0)
// Output: float2: 1.234000e+08

fmt.Printf("float3: %E\n", 123400000.0)
// Output: float3: 1.234000E+08

String Formatting

fmt.Printf("str1: %s\n", "\"string\"")
// Output: str1: "string"

fmt.Printf("str2: %q\n", "\"string\"")
// Output: str2: "\"string\""

fmt.Printf("str3: %x\n", "hex this")
// Output: str3: 6865782074686973

fmt.Printf("pointer: %p\n", &p)
// Output: pointer: 0xc0000140a0

Width and Precision

Integer Width

fmt.Printf("width1: |%6d|%6d|\n", 12, 345)
// Output: width1: |    12|   345|

Float Width and Precision

fmt.Printf("width2: |%6.2f|%6.2f|\n", 1.2, 3.45)
// Output: width2: |  1.20|  3.45|

fmt.Printf("width3: |%-6.2f|%-6.2f|\n", 1.2, 3.45)
// Output: width3: |1.20  |3.45  |

String Width

fmt.Printf("width4: |%6s|%6s|\n", "foo", "b")
// Output: width4: |   foo|     b|

fmt.Printf("width5: |%-6s|%-6s|\n", "foo", "b")
// Output: width5: |foo   |b     |

Formatting Functions

Printf
func(format string, a ...any) (n int, err error)
Prints formatted string to os.Stdout
Sprintf
func(format string, a ...any) string
Formats and returns a string without printing
Fprintf
func(w io.Writer, format string, a ...any) (n int, err error)
Formats and prints to an io.Writer
s := fmt.Sprintf("sprintf: a %s", "string")
fmt.Println(s)
// Output: sprintf: a string

fmt.Fprintf(os.Stderr, "io: an %s\n", "error")
// Writes to stderr

Package Reference

Build docs developers (and LLMs) love