Go fmt Package

Printf, Sprintf, Fprintf, format verbs, width & precision, the Stringer interface, Scan, and Errorf.

Printf Sprintf Fprintf Format verbs Stringer Scan / Sscanf Errorf %w
๐Ÿ–จ

Print Family

โ„น๏ธ
All three write to os.Stdout. Print adds spaces between operands only when neither is a string. Println always adds spaces and a trailing newline. Printf uses a format string.
Print, Println, Printf โ€” writing to stdout Print*
fmt.Print("Hello", "World")       // HelloWorld   (no space between strings)
fmt.Print(1, 2, 3)                // 1 2 3       (spaces between non-strings)

fmt.Println("Hello", "World")    // Hello World\n
fmt.Println(42, true)            // 42 true\n

name, age := "Alice", 30
fmt.Printf("Name: %s, Age: %d\n", name, age) // Name: Alice, Age: 30
fmt.Printf("%v %v %v\n", 1, "two", true)     // 1 two true
๐Ÿ“

Sprint Family

Sprintf โ€” format to a string Sprint*
// Sprintf returns a formatted string instead of printing it
s := fmt.Sprintf("Hello, %s! You are %d years old.", "Bob", 25)
// s = "Hello, Bob! You are 25 years old."

url := fmt.Sprintf("https://api.example.com/users/%d", userID)

// Sprint โ€” like Print but returns a string
s2 := fmt.Sprint("count:", 42)    // "count:42"  (no space: string + non-string)
s3 := fmt.Sprint(1, 2, 3)         // "1 2 3"    (spaces between non-strings)

// Sprintln โ€” always adds spaces and a trailing newline
s4 := fmt.Sprintln("Hello", "World") // "Hello World\n"
๐Ÿ“ค

Fprint Family

๐Ÿ’ก
The F-variants write to any io.Writer โ€” a file, HTTP response, buffer, or os.Stderr. This is the idiomatic way to write formatted output to arbitrary destinations.
Fprintf โ€” write formatted output to any writer Fprint*
// Write to stderr
fmt.Fprintf(os.Stderr, "error: %v\n", err)

// Write to a file
f, _ := os.Create("out.txt")
fmt.Fprintf(f, "result: %d\n", 42)

// Write to a buffer (bytes.Buffer implements io.Writer)
var buf bytes.Buffer
fmt.Fprintf(&buf, "Hello, %s!", "World")
s := buf.String()   // "Hello, World!"

// Write to an HTTP response (http.ResponseWriter is an io.Writer)
fmt.Fprintf(w, "Status: %s\n", status)

// Fprintf returns (n int, err error) โ€” bytes written and any write error
n, err := fmt.Fprintf(f, "%d\n", 99)
๐Ÿ”ฃ

Format Verbs

General verbs โ€” work on any value General
type Point struct{ X, Y int }
p := Point{1, 2}

fmt.Printf("%v\n",  p)   // {1 2}          โ€” default format
fmt.Printf("%+v\n", p)   // {X:1 Y:2}      โ€” with field names
fmt.Printf("%#v\n", p)   // main.Point{X:1, Y:2} โ€” Go syntax
fmt.Printf("%T\n",  p)   // main.Point     โ€” type name
fmt.Printf("%v\n",  42)  // 42
fmt.Printf("%v\n", true) // true
fmt.Printf("%v\n", []int{1, 2, 3}) // [1 2 3]
Integer verbs Integers
n := 255
fmt.Printf("%d\n", n)   // 255   decimal
fmt.Printf("%b\n", n)   // 11111111 binary
fmt.Printf("%o\n", n)   // 377   octal
fmt.Printf("%x\n", n)   // ff    hex lower
fmt.Printf("%X\n", n)   // FF    hex upper
fmt.Printf("%c\n", 65)  // A     unicode char
fmt.Printf("%U\n", 'A') // U+0041
Float & string verbs Float / String
f := 3.14159
fmt.Printf("%f\n",  f)  // 3.141590
fmt.Printf("%e\n",  f)  // 3.141590e+00
fmt.Printf("%g\n",  f)  // 3.14159  (shortest)

s := "hello"
fmt.Printf("%s\n",  s)  // hello
fmt.Printf("%q\n",  s)  // "hello" (quoted)
fmt.Printf("%x\n",  s)  // 68656c6c6f (hex)

// Pointer
x := 42
fmt.Printf("%p\n", &x) // 0xc0000b4010
๐Ÿ“

Width & Precision

โ„น๏ธ
Width is the minimum field width. Precision controls decimal places for floats, or maximum characters for strings. A - flag left-aligns. A 0 flag zero-pads instead of space-padding.
Width โ€” minimum field width, right-aligned by default Width
fmt.Printf("|%6d|\n", 42)      // |    42|   right-aligned, padded with spaces
fmt.Printf("|%-6d|\n", 42)     // |42    |   left-aligned
fmt.Printf("|%06d|\n", 42)     // |000042|   zero-padded
fmt.Printf("|%+6d|\n", 42)     // |   +42|   always show sign

fmt.Printf("|%10s|\n", "hi")   // |        hi|   right-aligned string
fmt.Printf("|%-10s|\n", "hi")  // |hi        |   left-aligned string
Precision โ€” decimal places for floats, max chars for strings Precision
fmt.Printf("%.2f\n", 3.14159)    // 3.14
fmt.Printf("%.4f\n", 3.14159)    // 3.1416
fmt.Printf("%8.2f\n", 3.14159)   // |    3.14|   width 8, 2 decimal places

fmt.Printf("%.5s\n", "Hello, World") // Hello   โ€” truncate string to 5 chars

// Use * to pass width/precision as an argument
fmt.Printf("%*d\n", 8, 42)         // |      42|
fmt.Printf("%.*f\n", 3, 3.14159)   // 3.142
Aligning a table with Printf Example
rows := []struct{ name string; score float64 }{
    {"Alice", 98.5},
    {"Bob", 87.123},
    {"Charlie", 100.0},
}
fmt.Printf("%-10s  %6s\n", "Name", "Score")
fmt.Printf("%-10s  %6s\n", "----------", "------")
for _, r := range rows {
    fmt.Printf("%-10s  %6.1f\n", r.name, r.score)
}
// Name        Score
// ----------  ------
// Alice         98.5
// Bob           87.1
// Charlie      100.0
๐ŸŽญ

Stringer & GoStringer

๐Ÿ’ก
Implement String() string on your type and fmt will call it automatically for %v, %s, and Println. Implement GoString() string for the %#v verb.
fmt.Stringer interface โ€” custom %v and %s output Stringer
type Direction int

const (
    North Direction = iota
    South
    East
    West
)

func (d Direction) String() string {
    return [...]string{"North", "South", "East", "West"}[d]
}

fmt.Println(North)          // North   (not 0)
fmt.Printf("%v\n", South)   // South
fmt.Printf("%s\n", East)    // East
fmt.Printf("%d\n", West)    // 3  (%d bypasses String())
fmt.GoStringer โ€” custom %#v output GoStringer
type Color struct{ R, G, B uint8 }

func (c Color) String() string {
    return fmt.Sprintf("#%02X%02X%02X", c.R, c.G, c.B)
}

func (c Color) GoString() string {
    return fmt.Sprintf("Color{R:%d, G:%d, B:%d}", c.R, c.G, c.B)
}

red := Color{255, 0, 0}
fmt.Printf("%v\n",  red) // #FF0000
fmt.Printf("%#v\n", red) // Color{R:255, G:0, B:0}
โš ๏ธ

Errorf

โš ๏ธ
Use %w (not %v) to wrap an error. Only %w lets callers use errors.Is and errors.As to inspect the wrapped error.
fmt.Errorf โ€” create and wrap errors Errorf
// Simple error with context (no wrapping)
err := fmt.Errorf("user %d not found", userID)

// %w wraps the original error โ€” callers can unwrap it
func loadUser(id int) (*User, error) {
    u, err := db.Query(id)
    if err != nil {
        return nil, fmt.Errorf("loadUser %d: %w", id, err)
    }
    return u, nil
}

// The caller can still inspect the original error
_, err = loadUser(99)
errors.Is(err, sql.ErrNoRows)  // true โ€” unwraps through the chain
๐Ÿ”

Scan Family

โ„น๏ธ
Scan* reads values into pointers. Sscanf parses from a string โ€” useful for parsing structured text. Fscanf reads from any io.Reader.
Sscanf โ€” parse structured strings Sscanf
// Sscanf(input, format, &vars...) โ†’ n int, err error
var name string
var age  int
n, err := fmt.Sscanf("Alice 30", "%s %d", &name, &age)
// n=2, err=nil, name="Alice", age=30

// Parse a log timestamp
var hour, min, sec int
fmt.Sscanf("14:05:09", "%d:%d:%d", &hour, &min, &sec)
// hour=14, min=5, sec=9

// Scan from stdin (blocks until user presses Enter)
var x int
fmt.Scan(&x)

// Scanf โ€” like Scan but with a format string
var s string
fmt.Scanf("%s", &s)
๐Ÿ“‹

Quick Reference

Verb Type Example output
%vanyDefault format: {1 2}, true, 42
%+vstructField names: {X:1 Y:2}
%#vanyGo syntax: main.Point{X:1, Y:2}
%TanyType name: main.Point, int, []string
%dintegerDecimal: 255
%bintegerBinary: 11111111
%ointegerOctal: 377
%x / %Xinteger/stringHex lowercase/uppercase: ff / FF
%cintegerUnicode character: A
%Uinteger/runeUnicode point: U+0041
%ffloatDecimal: 3.141590
%e / %EfloatScientific: 3.141590e+00
%g / %GfloatShortest representation: 3.14159
%sstring/[]byteUnquoted: hello
%qstring/runeDouble-quoted: "hello"
%ppointerHex address: 0xc0000b4010
%tbooltrue or false
%werror (Errorf only)Wrap error for errors.Is/As
Flag Effect Example
-Left-align within field width%-10s โ†’ "hi "
0Zero-pad (numbers)%06d โ†’ "000042"
+Always print sign for numbers%+d โ†’ "+42"
(space)Space before positive numbers% d โ†’ " 42"
#Alternate form: 0x prefix for hex, etc.%#x โ†’ "0xff"
Function Destination Notes
Print / Println / Printfos.StdoutReturns (n, err)
Sprint / Sprintln / SprintfstringReturns formatted string
Fprint / Fprintln / Fprintfio.WriterReturns (n, err)
Errorferror valueUse %w to wrap
Scan / Scanln / Scanfos.Stdin โ†’ varsReturns (n, err)
Sscan / Sscanfstring โ†’ varsParse structured strings
Fscan / Fscanfio.Reader โ†’ varsRead from any reader