Go Printf, in full fmt.Printf, prints formatted text: you give it a format string with placeholders such as %d, %s and %v, and it replaces each placeholder with the next argument. This guide covers the format verbs, width and padding, printing structs, slices and maps, the related functions Sprintf, Fprintf and Errorf, and the strange output you get (%!d(string=hi)) when verbs and arguments don’t match.
Here’s the short version:
package main
import "fmt"
func main() {
name := "Ada"
age := 36
score := 91.456
fmt.Printf("%s is %d years old\n", name, age)
fmt.Printf("Score: %.2f\n", score)
fmt.Printf("%v %v %v\n", name, age, score)
}Code language: Go (go)
Ada is 36 years old
Score: 91.46
Ada 36 91.456Code language: plaintext (plaintext)
%s is for strings, %d for integers, %.2f for a float with two decimals, and %v works for any value. If you remember only one verb, make it %v.
What fmt.Printf does (and why your newline is missing)
Printf stands for “print formatted”. The first argument is the format string. Everything in it is printed as is, except the verbs: a % followed by a letter. Each verb is replaced by the next argument, in order.
Unlike fmt.Println, Printf does not add a newline at the end. You have to write \n yourself. Forget it and the next thing you print lands on the same line:
package main
import "fmt"
func main() {
fmt.Printf("Loading %d files", 3)
fmt.Printf("Done")
fmt.Println()
fmt.Printf("Loading %d files\n", 3)
fmt.Printf("Done\n")
}Code language: Go (go)
Loading 3 filesDone
Loading 3 files
DoneCode language: plaintext (plaintext)
If the last line of your program has no \n, your shell prompt ends up glued to the output (zsh, the default shell on a Mac, shows a stray % there instead). That’s the number one Printf surprise for people coming from Println.
Go Printf format verbs (format specifiers)
C and Python call them format specifiers, Go calls them verbs. These are the ones you’ll use, with what each prints:
| Verb | Prints | Example value | Output |
|---|---|---|---|
%v | Any value in its default format | 42 | 42 |
%+v | Like %v, with struct field names | a struct | {Name:Ada Age:36} |
%#v | The value as Go source code | "go" | "go" |
%T | The type of the value | 42 | int |
%d | Integer, base 10 | 42 | 42 |
%s | String | "go" | go |
%q | Quoted string (or quoted character) | "go" | "go" |
%f | Float, six decimals | 3.14159 | 3.141590 |
%.2f | Float, two decimals (rounded) | 3.14159 | 3.14 |
%t | Boolean | true | true |
%x | Hexadecimal (%X for uppercase) | 255 | ff |
%c | The character for a Unicode code point | 71 or 'G' | G |
%U | Unicode code point notation | 'G' | U+0047 |
%p | Pointer address | &x | 0x3f2c8e012150 |
%b | Binary | 5 | 101 |
%e | Scientific notation | 1234.5678 | 1.234568e+03 |
%% | A literal percent sign, uses no argument | % |
And here they are in a program you can run:
package main
import "fmt"
func main() {
n := 42
pi := 3.14159
fmt.Printf("%v %d %b %x %X\n", n, n, n, n, n)
fmt.Printf("%v %f %.2f %e\n", pi, pi, pi, pi)
fmt.Printf("%v %s %q %x\n", "go", "go", "go", "go")
fmt.Printf("%v %c %q %U\n", 'G', 'G', 'G', 'G')
fmt.Printf("%v %t\n", true, true)
fmt.Printf("%T %T %T\n", n, pi, "go")
fmt.Printf("%d%% done\n", 50)
fmt.Printf("%[1]d is %[1]x in hex and %[1]b in binary\n", 255)
}Code language: Go (go)
42 42 101010 2a 2A
3.14159 3.141590 3.14 3.141590e+00
go go "go" 676f
71 G 'G' U+0047
true true
int float64 string
50% done
255 is ff in hex and 11111111 in binaryCode language: plaintext (plaintext)
A few things to notice:
%von'G'prints71. A character literal in Go is a number (a rune). Use%cto print it as a character. The strings lesson explains runes.%xworks on strings too. It prints the bytes in hex.- The last line uses an argument index.
%[1]dmeans “argument 1, as a decimal”, so you can print the same argument several times without repeating it. - There’s no verb for dates. Times are formatted with
time.Formatand a layout string, which works differently.
The fmt package documentation has the complete list, including the rarer ones like %o (octal) and %g (the shortest float representation, which is what %v uses for floats).
Print a struct with field names (%+v and %#v)
Plain %v prints only the values of a struct. To see the field names, use %+v. To see the type name as well, with strings quoted, use %#v:
package main
import "fmt"
type User struct {
Name string
Age int
Admin bool
}
func main() {
u := User{Name: "Ada", Age: 36, Admin: true}
fmt.Printf("%v\n", u)
fmt.Printf("%+v\n", u)
fmt.Printf("%#v\n", u)
fmt.Printf("%+v\n", &u)
}Code language: Go (go)
{Ada 36 true}
{Name:Ada Age:36 Admin:true}
main.User{Name:"Ada", Age:36, Admin:true}
&{Name:Ada Age:36 Admin:true}Code language: plaintext (plaintext)
I use %+v for quick debugging and %#v when I need to know exactly what a value is, for example to tell an empty string from a missing one. A pointer to a struct prints as &{...}, as the last line shows. That only works at the top level: a pointer stored in a struct field prints as an address like 0x3f2c8e012270.
Printf always prints a struct on one line. For indented, multi-line output of a big struct, json.MarshalIndent from the JSON lesson is the easiest route.
Print the type of a variable (%T)
%T prints the type of a value instead of the value itself. It’s handy when := picked a type for you and you want to know which one:
package main
import "fmt"
func main() {
x := 42
p := &x
var err error
fmt.Printf("%T\n", x)
fmt.Printf("%T\n", 3.14)
fmt.Printf("%T\n", "hi")
fmt.Printf("%T\n", 'a')
fmt.Printf("%T\n", p)
fmt.Printf("%T\n", []string{"a", "b"})
fmt.Printf("%T\n", map[string]int{})
fmt.Printf("%T\n", err)
}Code language: Go (go)
int
float64
string
int32
*int
[]string
map[string]int
<nil>Code language: plaintext (plaintext)
'a' shows up as int32 because rune is another name for int32. The err variable holds nothing yet, so there is no value to take the type of and you get <nil>. To keep the type name in a variable, use fmt.Sprintf("%T", x).
Printf width, padding and alignment
Between the % and the verb you can put a width, a precision and a few flags. The general shape is %[flags][width][.precision]verb. A number is the minimum width, padded with spaces on the left. A - pads on the right instead, and a 0 pads with zeros.
package main
import "fmt"
func main() {
pi := 3.14159
// Integers
fmt.Printf("|%5d|\n", 42)
fmt.Printf("|%-5d|\n", 42)
fmt.Printf("|%05d|\n", 42)
fmt.Printf("|%+d|\n", 42)
fmt.Printf("|%2d|\n", 12345)
// Strings
fmt.Printf("|%10s|\n", "go")
fmt.Printf("|%-10s|\n", "go")
fmt.Printf("|%.3s|\n", "golang")
// Floats: width.precision
fmt.Printf("|%8.2f|\n", pi)
fmt.Printf("|%-8.2f|\n", pi)
fmt.Printf("|%08.2f|\n", pi)
}Code language: Go (go)
| 42|
|42 |
|00042|
|+42|
|12345|
| go|
|go |
|gol|
| 3.14|
|3.14 |
|00003.14|Code language: plaintext (plaintext)
The width is a minimum. %2d with 12345 prints all five digits, nothing gets cut off. For floats, the width counts the whole number including the decimal point, so %08.2f means “eight characters in total, two of them decimals, zero-padded”. For strings, a precision (%.3s) does cut: it keeps the first three characters.
| Flag | Effect | Example | Output |
|---|---|---|---|
- | Left-align (pad on the right) | %-5d with 42 | 42 |
0 | Pad with zeros instead of spaces | %05d with 42 | 00042 |
+ | Always print the sign | %+d with 42 | +42 |
# | Alternate format, such as a 0x prefix | %#x with 255 | 0xff |
Print aligned columns
Widths are how you print a table. Use the same widths in the header and in every row, left-align the text and right-align the numbers:
package main
import "fmt"
type item struct {
name string
qty int
price float64
}
func main() {
items := []item{
{"Coffee", 2, 3.5},
{"Sandwich", 1, 7.25},
{"Cookie", 12, 0.8},
}
fmt.Printf("%-10s %5s %8s\n", "Item", "Qty", "Price")
for _, it := range items {
fmt.Printf("%-10s %5d %8.2f\n", it.name, it.qty, it.price)
}
}Code language: Go (go)
Item Qty Price
Coffee 2 3.50
Sandwich 1 7.25
Cookie 12 0.80Code language: plaintext (plaintext)
Set the width from a variable (%*d)
If the width isn’t known until the program runs, write * where the number would go. Printf then takes the width from the argument list, right before the value. It works for the precision too:
package main
import "fmt"
func main() {
width := 6
fmt.Printf("|%*d|\n", width, 42)
fmt.Printf("|%-*d|\n", width, 42)
fmt.Printf("|%.*f|\n", 1, 3.14159)
}Code language: Go (go)
| 42|
|42 |
|3.1|Code language: plaintext (plaintext)
Print slices, maps, pointers and errors
%v handles slices and maps without any loop. Other verbs are applied to each element, which gives you a few useful tricks:
package main
import "fmt"
func main() {
nums := []int{1, 2, 3}
names := []string{"Ada", "Grace Hopper"}
ages := map[string]int{"Grace": 85, "Ada": 36}
var empty []int
fmt.Printf("%v\n", nums)
fmt.Printf("%#v\n", nums)
fmt.Printf("%03d\n", nums)
fmt.Printf("%v\n", names)
fmt.Printf("%q\n", names)
fmt.Printf("%v\n", ages)
fmt.Printf("%#v\n", ages)
fmt.Printf("%v %#v\n", empty, empty)
}Code language: Go (go)
[1 2 3]
[]int{1, 2, 3}
[001 002 003]
[Ada Grace Hopper]
["Ada" "Grace Hopper"]
map[Ada:36 Grace:85]
map[string]int{"Ada":36, "Grace":85}
[] []int(nil)Code language: plaintext (plaintext)
Look at the two names lines. With %v you can’t tell whether the slice has two elements or three. %q quotes each one and removes the doubt, which is why I reach for it when debugging strings. Maps are printed sorted by key, so the output is the same on every run. For a different separator, such as commas, use strings.Join or a loop.
Pointers
A pointer prints as a memory address with both %p and %v. To print what it points to, dereference it with *:
package main
import "fmt"
func main() {
x := 42
p := &x
var nothing *int
fmt.Printf("%p\n", p)
fmt.Printf("%v\n", p)
fmt.Printf("%d\n", *p)
fmt.Printf("%v\n", nothing)
}Code language: Go (go)
0x3f2c8e012150
0x3f2c8e012150
42
<nil>Code language: plaintext (plaintext)
The address will be different on your machine, and usually on every run.
Errors
An error prints its message with %v or %s. A nil error prints as <nil>:
package main
import (
"errors"
"fmt"
)
func main() {
err := errors.New("file not found")
var none error
fmt.Printf("%v\n", err)
fmt.Printf("failed: %s\n", err)
fmt.Printf("%q\n", err)
fmt.Printf("%v\n", none)
}Code language: Go (go)
file not found
failed: file not found
"file not found"
<nil>Code language: plaintext (plaintext)
Print a bool
The verb for booleans is %t, and %v works as well. Both print the words true or false. There is no verb that prints a bool as yes/no or 1/0. For that, pick the text yourself with an if:
package main
import "fmt"
func main() {
admin := true
fmt.Printf("%t\n", admin)
fmt.Printf("%v\n", !admin)
fmt.Printf("|%6t|%-6t|\n", admin, admin)
answer := "no"
if admin {
answer = "yes"
}
fmt.Printf("Admin: %s\n", answer)
}Code language: Go (go)
true
false
| true|true |
Admin: yesCode language: plaintext (plaintext)
Using %d on a bool doesn’t give you 1. It prints %!d(bool=true). More on that kind of output further down.
Printf vs Println vs Print
The fmt package has three functions that print to the terminal. They differ in two things: whether they take a format string, and what they add for you.
| Function | Format string | Spaces between arguments | Newline at the end |
|---|---|---|---|
fmt.Println | No | Always | Yes |
fmt.Print | No | Only between two arguments that are both not strings | No |
fmt.Printf | Yes | Only what you write | No |
package main
import "fmt"
func main() {
name, age := "Ada", 36
fmt.Println("Name:", name, "Age:", age)
fmt.Print("Name:", name, "Age:", age, "\n")
fmt.Printf("Name: %s Age: %d\n", name, age)
}Code language: Go (go)
Name: Ada Age: 36
Name:AdaAge:36
Name: Ada Age: 36Code language: plaintext (plaintext)
My rule: Println for quick output of whole values, Printf as soon as I care about the layout. I rarely use Print. Println and Print format each argument the way %v would.
What doesn’t work is putting verbs in a Println call. Println doesn’t know about verbs and prints them literally: the program below would print %d items 3. Go’s built-in checker, go vet, catches the mistake:
package main
import "fmt"
func main() {
fmt.Println("%d items", 3)
}Code language: Go (go)
main.go:6:2: fmt.Println call has possible Printf formatting directive %dCode language: plaintext (plaintext)
Sprintf: format to a string instead of printing
fmt.Sprintf takes the same format string and verbs as Printf, but returns the result as a string instead of printing it. Use it whenever you need the formatted text for something else: a file name, a message, a map key.
package main
import "fmt"
func main() {
name := "Ada"
msg := fmt.Sprintf("Hello, %s! You have %d new messages.", name, 3)
fmt.Println(msg)
file := fmt.Sprintf("report-%04d.txt", 42)
fmt.Println(file)
}Code language: Go (go)
Hello, Ada! You have 3 new messages.
report-0042.txtCode language: plaintext (plaintext)
Everything in this guide applies to Sprintf as well. For a plain number-to-string conversion with no formatting around it, strconv.Itoa is the more direct tool. The strings lesson covers it.
Fprintf: print to os.Stderr, a file or any writer
fmt.Fprintf has one extra argument in front: where to write. That can be anything with a Write method (an io.Writer): os.Stdout, os.Stderr, a file, a strings.Builder, or the response of an HTTP server. Printf itself is Fprintf with os.Stdout filled in.
package main
import (
"fmt"
"os"
"strings"
)
func main() {
fmt.Fprintf(os.Stdout, "processed %d files\n", 3)
var sb strings.Builder
fmt.Fprintf(&sb, "%d-%d", 2026, 11)
fmt.Println(sb.String())
fmt.Fprintf(os.Stderr, "error: cannot open %s\n", "data.csv")
}Code language: Go (go)
processed 3 files
2026-11
error: cannot open data.csvCode language: plaintext (plaintext)
Error messages belong on standard error, so they stay visible when someone redirects your program’s normal output to a file. In the terminal both streams look the same.
Errorf and %w: format an error
fmt.Errorf is Sprintf that returns an error instead of a string. It has one verb of its own, %w, which wraps another error so the original stays reachable for errors.Is and errors.As:
package main
import (
"errors"
"fmt"
)
var errNotFound = errors.New("file not found")
func loadConfig(path string) error {
return fmt.Errorf("load config %q: %w", path, errNotFound)
}
func main() {
err := loadConfig("app.toml")
fmt.Println(err)
fmt.Println(errors.Is(err, errNotFound))
}Code language: Go (go)
load config "app.toml": file not found
trueCode language: plaintext (plaintext)
With %v in place of %w the message is identical, but errors.Is returns false because only the text was copied. %w works in Errorf only. The errors lesson explains wrapping in detail.
Wrong verbs and wrong argument counts: %!d(string=hi), %!v(MISSING) and %!(EXTRA
Printf never crashes on a bad format string, and the compiler doesn’t check it. Instead, the mistake shows up in the output as text starting with %!. This program contains the classic golang printf mistakes:
package main
import "fmt"
func main() {
fmt.Printf("%d\n", "hi")
fmt.Printf("%s\n", 42)
fmt.Printf("%v and %v\n", "one")
fmt.Printf("%d\n", 1, 2)
fmt.Printf("%z\n", 1)
fmt.Printf("100% done\n")
}Code language: Go (go)
Run go vet . in the program’s folder and it reports every one of the six lines:
main.go:6:14: fmt.Printf format %d has arg "hi" of wrong type string
main.go:7:14: fmt.Printf format %s has arg 42 of wrong type int
main.go:8:21: fmt.Printf format %v reads arg #2, but call has 1 arg
main.go:9:2: fmt.Printf call needs 1 arg but has 2 args
main.go:10:14: fmt.Printf format %z has unknown verb z
main.go:11:17: fmt.Printf format % d reads arg #1, but call has 0 argsCode language: plaintext (plaintext)
go run and go build don’t run vet, though, so the program builds fine. This is what it prints:
%!d(string=hi)
%!s(int=42)
one and %!v(MISSING)
1
%!(EXTRA int=2)%!z(int=1)
100%!d(MISSING)oneCode language: plaintext (plaintext)
Each of these has a fixed shape that tells you what went wrong:
| Output | Meaning | Fix |
|---|---|---|
%!d(string=hi) | The verb doesn’t fit the type. You get the verb, then the actual type and value. | Use a verb that fits (%s), or %v. |
%!v(MISSING) | More verbs than arguments. | Add the argument or remove the verb. |
%!(EXTRA int=2) | More arguments than verbs. The leftovers are printed at the end, after your newline. | Add a verb or remove the argument. |
%!z(int=1) | %z is not a verb. | Check the verb table above. |
%!(NOVERB) | The format string ends in a single %. | Write %%. |
The last line of the program is the sneaky one. I wanted a percent sign, but Printf read % d as a verb (a space is a valid flag), found no argument for it, and swallowed the “d” of “done”. A literal percent sign is always %%.
Let go vet find Printf mistakes
So you don’t have to find these mistakes by reading output. Run go vet . before you commit, or let your tools do it: most editors with Go support show the same warnings while you type, and go test runs this check before your tests. If you see %! anywhere in your output, go vet will point at the line.
One more vet message you’re likely to meet is non-constant format string. It appears when you pass a variable as the format string with no other arguments:
package main
import "fmt"
func main() {
msg := "50% off"
fmt.Printf(msg)
}Code language: Go (go)
main.go:7:13: non-constant format string in call to fmt.PrintfCode language: plaintext (plaintext)
The danger is that any % inside the variable gets treated as a verb. This one prints 50%!o(MISSING)ff. Use fmt.Print(msg), or fmt.Printf("%s", msg).
Control what %v prints with a String method
If a type has a method with the signature String() string, then %v, %s and Println call it and print the result. Such a type satisfies the fmt.Stringer interface:
package main
import "fmt"
type Celsius float64
func (c Celsius) String() string {
return fmt.Sprintf("%.1f°C", float64(c))
}
func main() {
t := Celsius(21.5)
fmt.Printf("%v\n", t)
fmt.Printf("%s\n", t)
fmt.Println(t)
fmt.Printf("%.2f\n", t)
fmt.Printf("%#v\n", t)
}Code language: Go (go)
21.5°C
21.5°C
21.5°C
21.50
21.5Code language: plaintext (plaintext)
Verbs that ask for a specific format, like %.2f, and %#v skip the method and print the underlying value. Notice the float64(c) conversion inside String. Formatting c itself with %v there would call String again, and again, until the program runs out of stack. (go vet catches that one too.) Errors work the same way: for a value with an Error() string method, %v prints what that method returns.
Key takeaways
fmt.Printfreplaces each verb in the format string with the next argument and adds no newline. End the format with\n.%vprints anything.%+vadds struct field names,%#vprints Go syntax,%Tprints the type, and%qmakes strings unambiguous.- Width and flags go between
%and the verb:%5dpads left,%-10spads right,%08.2fzero-pads a float,%*dreads the width from an argument. Sprintfreturns a string,Fprintfwrites to any writer such asos.Stderr, andErrorfwith%wbuilds a wrapped error.- Output containing
%!means the verbs and arguments don’t match.go vetfinds those mistakes before you run the program.