View source code
Display the source code in std/format/package.d from which this page was generated on github.
Report a bug
If you spot a problem with this page, click here to create a Bugzilla issue.
Improve this page
Quickly fork, edit online, and submit a pull request for this page. Requires a signed-in GitHub account. This works well for small changes. If you'd like to make larger changes you may want to consider using local clone.

Function std.format.sformat

Converts its arguments according to a format string into a buffer. The buffer has to be large enough to hold the formatted string.

char[] sformat(Char, Args...) (
  scope return char[] buf,
  scope const(Char)[] fmt,
  Args args

char[] sformat(alias fmt, Args...) (
  char[] buf,
  Args args
if (isSomeString!(typeof(fmt)));

The second version of sformat takes the format string as a template argument. In this case, it is checked for consistency at compile-time.


buf the buffer where the formatted string should go
fmt a format string
args a variadic list of arguments to be formatted
Char character type of fmt
Args a variadic list of types of the arguments


A slice of buf containing the formatted string.


A RangeError if buf isn't large enough to hold the formatted string and a FormatException if formatting did not succeed.


In theory this function should be @nogc. But with the current implementation there are some cases where allocations occur:

  • An exception is thrown.
  • A custom toString function of a compound type allocates.


char[20] buf;
writeln(sformat(buf[], "Here are %d %s.", 3, "apples")); // "Here are 3 apples."

writeln(buf[].sformat("Increase: %7.2f %%", 17.4285)); // "Increase:   17.43 %"


The format string can be checked at compile-time:

char[20] buf;

writeln(sformat!"Here are %d %s."(buf[], 3, "apples")); // "Here are 3 apples."

// This line doesn't compile, because 3.14 cannot be formatted with %d:
// writeln(sformat!"Here are %d %s."(buf[], 3.14, "apples"));


Walter Bright, Andrei Alexandrescu, and Kenji Hara


Boost License 1.0.