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.
label := fmt.Sprintf("%s-%03d", "item", 7) // item-007
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 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 vetfinds them at build time. Sprintlnalways ends with a newline and puts spaces between all operands.
Usage notes
- Do not call
Sprintfjust to convert one value:strconv.Itoa(n)orstrconv.FormatFloatare faster and allocate less. - Do not build big strings by repeated
s += fmt.Sprintf(...). Usestrings.Builderwithfmt.Fprintf(&b, ...), as in the example. - If a
String()method usesSprintf("%v", x)on its own receiver, it recurses forever. Convert first:Sprintf("%d", int(x))orSprintf("%v", T(x))with an unmethoded alias type. - Never use
Sprintfto assemble SQL or shell commands from user input. Use parameters or argument lists. - For error values, use
fmt.Errorf; for log lines, pass attributes tosloginstead of formatting by hand. Sprintf("%v", x)andSprint(x)give the same result for one operand; the former is explicit.Sprintf("%s", err)callsError(), andSprintf("%s", nil)gives%!s(<nil>).- Dates should be built with
time.Format, not withSprintfon separate fields.