Skip to content

String Formatting

This section describes how to use the format() command to format strings.

Normally, strings are concatenated by using addition (+) between strings. Such as:

string s = "Hello" + " World";

When you want to include a different type it must be cast to a string first, which can make the code more complicated and harder to follow.

i32 x, y = 5, 20;
string location = "Location = " + x as string + ", " + y as string;

The format function makes this much easier. Each input parameter is concatenated and automatically casted to a string if needed.

string location = format("Location = ", x, ", ", y);

Format also allows injecting code from inside the string. When you use this feature the compiler simply reformats it into the expanded form.

string location = format("Location = {x}, {y}"); // same as below
// compiler converts the above into this form automatically.
string location = format("Location = ", x, ", ", y);

You can also leave the braces { } empty and the compiler will look ahead and grab the next parameter. This is a convenience but it can become confusing if you mix it with parameter concatenation.

// All of these have the same result: "Location = 5, 20".
// x and y added directly
string location = format("Location = {x}, {y}");
// y added using concatenation
string location = format("Location = {x}, ", y);
// x and y added using look ahead
string location = format("Location = {}, {}", x, y);
// x added using look ahead, y added directly
string location = format("Location = {}, {y}", x);
// x and y added using concatenation
string location = format("Location = ", x, ", ", y);
// x and y added using look ahead
string location = format("Location = {}", x, ", {}", y);

All of these features are also present when using the print() and println() commands.

println("Location = " + x as string + ", " + y as string);
println(format("Location = {x}, {y}")); // same as above
println("Location = {x}, {y}"); // same as above