Tuples and text
Now that we’ve gone over the basic types, you might have wondered about a detail in the hello_user.zig file: What’s that .{} symbol in the call to the print function?
|
std.debug.print("\nHello, user.\n", .{}); |
That’s a data structure called a tuple. Specifically, .{} is an empty tuple.
The print function expects a tuple as its second argument. It doesn’t have to be empty. A tuple is a simple data structure that can also hold multiple values at once. We could have something like this with a value:
hello_user_2.zig |
|
const std = @import("std"); pub fn main() void { const s_name = "Programmer"; std.debug.print( \\Hello, {s}, \\I was waiting for you. \\ , .{s_name}); } |
|
$ zig run hello_user_2.zig |
|
Hello, Programmer I was waiting for you. |
You can use your own name as the value of the s_name string instead of "Programmer".
This time, the string we wrote starts with a double backslash \\ and spans multiple lines. That means it's a multiline string, and the line breaks are included automatically with each new line.
As you can see, the string \\Hello, {s}, now also contains {s}. This symbol tells Zig to insert a value from the tuple.
{s} means that the value is a string (the s stands for string). If the value were a number, we couldn't use {s} as the placeholder - we'd need a different letter, such as {d} (where d stands for decimal).
We could also pass more data in the tuple:
hello_user_3.zig |
|
const std = @import("std"); pub fn main() void { const s_name = "Programmer"; const n_age = 20; std.debug.print("\nHello, {s}.\nYou are {b} years old.\n", .{ s_name, n_age }); } |
|
$ zig run hello_user_3.zig |
|
Hello, Programmer. You are 10100 years old. |
10100 years?
Why do we get that output if n_age has the value 20? Take your time to think about it.
Notice that we’re using the insertion placeholder {b}. What could that b mean for 20 to turn into 10100?
Data Formats in a String
Here’s a table of these placeholders to help you out:
|
{s} |
Text string: "Hello", "Programmer" |
|
{d} |
Number printed in decimal format: 1, 3, 42, 23, etc. |
|
{b} |
Number printed in binary: 0001, 0010… |
|
{x} |
Number printed in lowercase hexadecimal: 255 as ff |
|
{X} |
Number printed in uppercase hexadecimal: 255 as FF |
|
{c} |
A character (such as a u8 interpreted as ASCII): 97 is 'a' |
|
{} |
Zig will try to detect the type |
As you may have figured out, {b} means the number passed in the tuple will be printed in binary format in the string.
If we use {} or {d}, the result will be printed in the decimal format we’re used to:
hello_user_4.zig |
|
const std = @import("std"); pub fn main() void { const s_name = "Programmer"; const n_age = 20; std.debug.print("\nHello, {s}.\nYou are {d} years old.\n", .{ s_name, n_age }); } |
|
$ zig run hello_user_4.zig |
|
Hello, Programmer. You are 20 years old. |