Go by Example

String Formatting

Format values with fmt verbs and choose between printing, writing, or returning a string.

The fmt package turns values into text using format verbs, short codes beginning with %. For example, %v prints a usual representation, %+v includes struct field names, %#v prints Go-style code, 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 %w to add a message to an error while keeping the original error available to callers. Use fmt.Fprintf to write formatted text directly to a file or terminal instead of making a separate string first.

Enjoyed this? Get more software craft delivered to your inbox.