Skip to main content

Format Strings

The Hack typechecker checks that format strings are being used correctly.

Quick Start

// Correct.
Str\format("First: %d, second: %s", 1, "foo");

// Typechecker error: Too few arguments for format string.
Str\format("First: %d, second: %s", 1);

This requires that the format string argument is a string literal, not a variable.

$string = "Number is: %d";

// Typechecker error: Only string literals are allowed here.
Str\format($string, 1);

Defining Functions with Format Strings

You can define your own functions with format string arguments too.

function takes_format_string(
\HH\FormatString<\PlainSprintf> $format,
mixed ...$args
): void {}

function use_it(): void {
takes_format_string("First: %d, second: %s", 1, "foo");
}

HH\FormatString<PlainSprintf> will check that you've used the right number of arguments. HH\FormatString<Str\SprintfFormat> will also check that arguments match the type in the format string.

Format Specifiers

See PlainSprintf for in-depth information on all format specifiers.

SpecifierExpected InputExpected Output
bintBinary (63 => 111111)
cintASCII character (63 => ?)
dintSigned int (-1 => -1)
uintUnsigned int (-1 => 18446744073709551615)
efloatScientific Notation, as lowercase (0.34 => 3.4e)
EfloatScientific Notation, as uppercase (0.34 => 3.4E)
ffloatLocale Floating Point Number
FfloatNon-Locale Floating Point Number
gfloatLocale Floating Point Number or Scientific Notation (3.141592653 => 3.14159, 3141592653 => 3.1415e+9).
ointOctal (63 => 77)
sstringstring
xintHexadecimal, as lowercase (63 => 3f)
XintHexadecimal, as uppercase (63 => 3F)