Formatted Output with fmt
Prerequisites: Strings, bytes & runes
The fmt package has three families of printing functions:
fmt.Print/fmt.Println— print values as they are (Printlnadds spaces between arguments and a newline at the end).fmt.Printf— print using a format string with verbs like%d. It does not add a newline — write\nyourself.fmt.Sprintf— same asPrintf, but returns the string instead of printing it.
Syntax
The verbs you'll use most:
%v— the value in a default format (works for anything)%+v— like%v, but includes field names for structs%T— the value's type%d— an integer%s— a string%q— a string in double quotes, with special characters escaped%.2f— a float with 2 decimal places%5d/%-5s— pad to a width of 5 (right / left aligned)%%— a literal percent sign
Example
package main
import "fmt"
// Point is a struct — you'll learn structs in a later lesson.
type Point struct {
X, Y int
}
func main() {
name := "Ada"
age := 36
price := 19.5
p := Point{X: 1, Y: 2}
fmt.Printf("%v %v %v\n", name, age, price)
fmt.Printf("%v | %+v\n", p, p)
fmt.Printf("%T %T %T %T\n", name, age, price, p)
fmt.Printf("%d years\n", age)
fmt.Printf("Hello, %s!\n", name)
fmt.Printf("%q\n", name)
fmt.Printf("%.2f\n", price)
fmt.Printf("[%5d] [%-5s]\n", 42, "go")
fmt.Printf("%d%%\n", 50)
msg := fmt.Sprintf("%s is %d years old", name, age)
fmt.Println(msg)
}
Expected output
Ada 36 19.5
{1 2} | {X:1 Y:2}
string int float64 main.Point
36 years
Hello, Ada!
"Ada"
19.50
[ 42] [go ]
50%
Ada is 36 years old
Common mistakes
- Forgetting
\nat the end of aPrintfformat string, so the next output runs onto the same line. - Using the wrong verb for a value. The program still compiles,
but prints something like
%!d(string=Ada). Rungo vet— it catches these mismatches:
./main.go:8:5: fmt.Printf format %d has arg name of wrong type string
- Passing a format string to
Println— it prints the%verbs literally instead of substituting values.
Practice
With item := "Coffee" and price := 3.5, print exactly
Coffee costs $3.50 using Printf. Then build the same text with
Sprintf and print its length.
Show solution
package main
import "fmt"
func main() {
item := "Coffee"
price := 3.5
fmt.Printf("%s costs $%.2f\n", item, price)
text := fmt.Sprintf("%s costs $%.2f", item, price)
fmt.Println(len(text)) // 18
}