Skip to content
Tutorials Center
My learning

Topics

Go Reference ยท fmt Package

Go fmt.Sprintf() function

Reference for Go fmt.Sprintf(): build strings from a format string and values, with common patterns, padding, type pitfalls and faster alternatives.

fmt.Sprintf works exactly like Printf, except that it returns the formatted text as a string instead of printing it. It is the general-purpose way to build messages, keys, file names and labels from mixed values.

Because it uses reflection and allocates, it is perfect for readable code but not the fastest way to turn one integer into a string; for that, strconv.Itoa is better.

Go
label := fmt.Sprintf("%s-%03d", "item", 7)
// item-007

Try it

Go Building strings

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 Sprint, Sprintln and alternatives

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 Sprintf(format string, a ...any) string
func Sprint(a ...any) string
func Sprintln(a ...any) string
Name Description
format A format string with verbs such as %s, %d, %v, %.2f.
a The values to format.

Returns the formatted string. There is no error return.

Edge cases

  • Bad verbs or wrong argument counts do not fail; they insert markers like %!d(string=oops) or %!d(MISSING) in the result. go vet finds them at build time.
  • Sprintln always ends with a newline and puts spaces between all operands.

Usage notes

  • Do not call Sprintf just to convert one value: strconv.Itoa(n) or strconv.FormatFloat are faster and allocate less.
  • Do not build big strings by repeated s += fmt.Sprintf(...). Use strings.Builder with fmt.Fprintf(&b, ...), as in the example.
  • If a String() method uses Sprintf("%v", x) on its own receiver, it recurses forever. Convert first: Sprintf("%d", int(x)) or Sprintf("%v", T(x)) with an unmethoded alias type.
  • Never use Sprintf to assemble SQL or shell commands from user input. Use parameters or argument lists.
  • For error values, use fmt.Errorf; for log lines, pass attributes to slog instead of formatting by hand.
  • Sprintf("%v", x) and Sprint(x) give the same result for one operand; the former is explicit.
  • Sprintf("%s", err) calls Error(), and Sprintf("%s", nil) gives %!s(<nil>).
  • Dates should be built with time.Format, not with Sprintf on separate fields.