How to declare a multiline string in Zig?

450 Views Asked by At

How can I write a string that spans over multiple lines in Zig?

For example:

var str = `hello
second line
world
fourth line
`
2

There are 2 best solutions below

1
On

Zig has this weird but cool syntax with multiple lines starting with \\ and the ; in the next line.

Here's a singleton:

const str =
    \\hello
    \\second line
    \\world
    \\fourth line
;

Here is an array of 2 multiline strings:

const array_of_multiline_strings = [_][]const u8{
    \\hello
    \\world
    ,
    \\goodbye
    \\world
};
0
On

Following the previous excellent response, it seems like you are referring to the Zig documentation, specifically section 5.3.2, Multiline-String-Literals. I believe implementing this example would look something like this:

const print = @import("std").debug.print;
const mem = @import("std").mem; // will be used to compare bytes

const hello_world_in_c =
    \\#include <stdio.h>
    \\
    \\int main(int argc, char **argv) {
    \\    printf("hello world\n");
    \\    return 0;
    \\}
;

pub fn main() void {
    print("{s}\n", .{hello_world_in_c});
}

Output:

include <stdio.h>

int main(int argc, char **argv) {
    printf("hello world\n");
    return 0;
}