Skip to content
Tutorials Center
My learning

Topics

Go Reference ยท fmt Package

Go fmt.Fprintf() function

Reference for Go fmt.Fprintf(), Fprintln and Fprint: write formatted text to files, buffers, HTTP responses and os.Stderr through the io.Writer interface.

fmt.Fprintf formats text like Printf but writes it to any io.Writer you choose: a file, os.Stderr, a bytes.Buffer, a strings.Builder, an HTTP response, a network connection or a bufio.Writer. The F stands for "file", but anything with a Write([]byte) method works.

Fprintln and Fprint complete the family. In fact Printf is just Fprintf(os.Stdout, ...).

Go
fmt.Fprintf(os.Stderr, "warning: %s\n", msg)

Try it

Go Different writers

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

Go Writing through your own io.Writer

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

Syntax

Go
func Fprintf(w io.Writer, format string, a ...any) (n int, err error)
func Fprintln(w io.Writer, a ...any) (n int, err error)
func Fprint(w io.Writer, a ...any) (n int, err error)
Name Description
w The destination. Anything implementing Write(p []byte) (n int, err error).
format The format string (Fprintf only).
a Values to format.

Returns

  • n: bytes written.
  • err: the first error returned by the writer, such as a closed pipe or a full disk.

Usage notes

  • Design functions that produce output to accept an io.Writer and call Fprintf on it. Tests then pass a bytes.Buffer and compare the text, while production code passes os.Stdout or a file.
  • Always check the error when writing to files and network connections. For bytes.Buffer and strings.Builder, errors are always nil.
  • fmt formats the whole result into an internal buffer and calls Write once, so a single call is not split into many small writes.
  • Wrap files or sockets in bufio.NewWriter when printing many small pieces, and call Flush at the end.
  • Use os.Stderr for diagnostics so they stay out of piped output. The log package already does this by default.
  • In an HTTP handler, fmt.Fprintf(w, ...) writes the response body. For HTML or JSON use templates or encoders to get escaping right.
  • io.Discard is a writer that throws everything away; handy for benchmarks.
  • Don't write Fprintf(w, userText); use Fprint(w, userText) or Fprintf(w, "%s", userText).