Skip to content

Go String Formatting

String formatting is how you build complex strings from variables. Go uses "verbs" (like %d) to tell the program how to format each value.

Common Tasks

1. Building a simple string

Use fmt.Sprintf to create a new string without printing it to the console.

s := fmt.Sprintf("A %s and a %d", "string", 123)
fmt.Println(s) // "A string and a 123"

2. Formatting Numbers

  • Decimal: %d
  • Float: %f (or %.2f for two decimal places)
  • Binary: %b
fmt.Printf("%.2f\n", 3.14159) // 3.14
fmt.Printf("%b\n", 15)      // 1111

3. Working with Structs

Use %+v to see the field names of a struct.

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

4. Padding and Alignment

Use numbers after the % to set the width.

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

Reference Table

Verb Description
%v The default value.
%T The type of the value.
%t Boolean (true/false).
%d Signed decimal integer.
%f Floating point number.
%s String.
%p Pointer (memory address).