Print Family
Print ยท Println ยท PrintfAll 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
Sprint ยท Sprintln ยท Sprintf
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
Fprint ยท Fprintln ยท FprintfThe
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
%v ยท %d ยท %s ยท %f ยท %p
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
%5d ยท %-10s ยท %.2f ยท %08dWidth 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
String() ยท GoString()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
fmt.Errorf ยท %w wrappingUse
%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 ยท Scanf ยท Sscanf ยท FscanfScan* 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
Verbs ยท Flags ยท Functions| Verb | Type | Example output |
|---|---|---|
| %v | any | Default format: {1 2}, true, 42 |
| %+v | struct | Field names: {X:1 Y:2} |
| %#v | any | Go syntax: main.Point{X:1, Y:2} |
| %T | any | Type name: main.Point, int, []string |
| %d | integer | Decimal: 255 |
| %b | integer | Binary: 11111111 |
| %o | integer | Octal: 377 |
| %x / %X | integer/string | Hex lowercase/uppercase: ff / FF |
| %c | integer | Unicode character: A |
| %U | integer/rune | Unicode point: U+0041 |
| %f | float | Decimal: 3.141590 |
| %e / %E | float | Scientific: 3.141590e+00 |
| %g / %G | float | Shortest representation: 3.14159 |
| %s | string/[]byte | Unquoted: hello |
| %q | string/rune | Double-quoted: "hello" |
| %p | pointer | Hex address: 0xc0000b4010 |
| %t | bool | true or false |
| %w | error (Errorf only) | Wrap error for errors.Is/As |
| Flag | Effect | Example |
|---|---|---|
| - | Left-align within field width | %-10s โ "hi " |
| 0 | Zero-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 / Printf | os.Stdout | Returns (n, err) |
| Sprint / Sprintln / Sprintf | string | Returns formatted string |
| Fprint / Fprintln / Fprintf | io.Writer | Returns (n, err) |
| Errorf | error value | Use %w to wrap |
| Scan / Scanln / Scanf | os.Stdin โ vars | Returns (n, err) |
| Sscan / Sscanf | string โ vars | Parse structured strings |
| Fscan / Fscanf | io.Reader โ vars | Read from any reader |