fmt

fmt printing verbs, Sprint helpers, Fprint write errors, and Errorf wrapping with %w.

模块页正文目前为英文。

The fmt package formats arguments and writes them to an io.Writer, to a string, or to standard output. It is part of the standard library, not a language built-in and not a third-party module.

Print, Fprint, and Sprint share the same formatting rules. The difference is the destination, and whether a write error can be observed. This page documents the verbs and error paths used most often, not every helper in the package.

Examples were checked against Go 1.24.0. See the official package documentation for the complete API.

Go reference overview →

API index

APISummary
fmt.Print, fmt.Println, fmt.Printf, fmt.SprintfWrite formatted operands to standard output, or build a string with Sprintf. Choose Println, Print, or a format verb explicitly; they do not space values the same way.
fmt.Fprint, fmt.Fprintln, fmt.FprintfWrite formatted output to w and return the byte count together with any write error from the underlying writer.
fmt.ErrorfConstruct an error from a format string. Use %w to wrap an existing error so callers can match it with errors.Is or errors.As.

Print, Println, and Printf

Println inserts a space between operands that are not strings and always appends a newline. Print does not insert that space and does not add a newline on its own. Printf uses a format string: %v is the default format, %+v adds field names on structs, %#v is a Go-syntax representation, %d is a decimal integer, and %q is a quoted string.

Sprint, Sprintf, and Sprintln return a string instead of writing to standard output. Their formatting rules match the corresponding Print functions.

Fprint and I/O errors

Fprint, Fprintf, and Fprintln write to any io.Writer. Unlike a format string that merely looks wrong, a failed write returns an error you can handle: a full disk, a closed pipe, or a failed HTTP response body are all visible here.

Do not ignore the error value when the writer is a file, a network connection, or another destination that can fail. bytes.Buffer rarely fails, which makes it useful in tests, but that is not representative of real I/O.

fmt.Fprint, fmt.Fprintln, fmt.Fprintf

func Fprint(w io.Writer, a ...any) (n int, err error)
func Fprintln(w io.Writer, a ...any) (n int, err error)
func Fprintf(w io.Writer, format string, a ...any) (n int, err error)

Write formatted output to w and return the byte count together with any write error from the underlying writer.

ParameterDescription
wThe destination. Any type that implements io.Writer, including *os.File, bytes.Buffer, and network connections.
a / formatThe same operands and format verbs as the corresponding Print functions.

Returns: The number of bytes written and the first error encountered. If the writer reports a short write, fmt returns that error rather than silently truncating.

Errors

  • error — Whatever the writer returns, such as a file-system error. There is no additional fmt-specific error type for a failed write.
  • Fprintln("ok") writes the three bytes o, k, and a newline when the write succeeds.
  • The Print functions that target standard output have the same (n, err) result. Fprint is the form that makes the failure path obvious.
go
package main

import (
	"bytes"
	"fmt"
)

type rejectWriter struct{}

func (rejectWriter) Write([]byte) (int, error) {
	return 0, fmt.Errorf("disk full")
}

func main() {
	var buf bytes.Buffer
	n, err := fmt.Fprintln(&buf, "ok")
	fmt.Printf("n=%d err=%v out=%q\n", n, err, buf.String())

	_, err = fmt.Fprintln(rejectWriter{}, "nope")
	fmt.Printf("write failed: %v\n", err)
}

Expected output

n=3 err=<nil> out="ok\n"
write failed: disk full

Related: io.Writer

Official documentation →

Errorf and wrapping

fmt.Errorf returns an error value. The %w verb wraps another error so that errors.Is and errors.As can inspect the chain. Other verbs, including %v, format the wrapped error as text but do not add it to the chain.

fmt.Errorf

func Errorf(format string, a ...any) error

Construct an error from a format string. Use %w to wrap an existing error so callers can match it with errors.Is or errors.As.

ParameterDescription
formatA format string. Include %w exactly once when you want to wrap an error.
aFormat operands. The operand for %w must implement the error interface.

Returns: An error whose Error() text is the formatted string. When %w is used, the result unwraps to the wrapped error.

  • errors.Is walks the chain created by %w. Formatting the same error with %v does not make errors.Is succeed.
  • The errors package is also in the standard library. It is not a third-party wrapper library.
go
package main

import (
	"errors"
	"fmt"
)

func main() {
	root := fmt.Errorf("permission denied")
	err := fmt.Errorf("open %s: %w", "a.txt", root)
	fmt.Println(err)
	fmt.Println(errors.Is(err, root))
}

Expected output

open a.txt: permission denied
true

Related: errors.Is

Official documentation →