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, ...).
fmt.Fprintf(os.Stderr, "warning: %s\n", msg)
Try it
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.
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
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.Writerand callFprintfon it. Tests then pass abytes.Bufferand compare the text, while production code passesos.Stdoutor a file. - Always check the error when writing to files and network connections. For
bytes.Bufferandstrings.Builder, errors are alwaysnil. fmtformats the whole result into an internal buffer and callsWriteonce, so a single call is not split into many small writes.- Wrap files or sockets in
bufio.NewWriterwhen printing many small pieces, and callFlushat the end. - Use
os.Stderrfor diagnostics so they stay out of piped output. Thelogpackage 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.Discardis a writer that throws everything away; handy for benchmarks.- Don't write
Fprintf(w, userText); useFprint(w, userText)orFprintf(w, "%s", userText).