String Formatting
Format values with fmt verbs and choose between printing, writing, or returning a string.
The fmt package formats values with verbs. For example, %v prints a default representation, %+v includes struct field names, %#v prints Go syntax, and %T prints the value's type.
Printf writes formatted text, Sprintf returns it as a string, and Fprintf writes it to a supplied destination.
package main
import (
"fmt"
"os"
)
type Point struct {
X, Y int
}
func main() {
p := Point{3, 4}
fmt.Printf("%+v (%T)\n", p, p)
message := fmt.Sprintf("count: %d", 3)
fmt.Println(message)
fmt.Fprintf(os.Stdout, "%#v\n", p)
}In production
Use fmt.Errorf with the %w verb to wrap an error when callers need to inspect the cause with errors.Is or errors.As. Prefer Fprintf when writing directly to an io.Writer instead of building an intermediate string first.
Enjoyed this? Get more software craft delivered to your inbox.