Search code examples
zig

Multiline string is invalid


I'm writting the below code:

pub fn main() !void {
    var array_list = std.ArrayList([]const u8).init(std.heap.page_allocator);
    defer array_list.deinit();
    const cwd = fs.cwd();
    const file = try cwd.createFile("files.zig", .{});
    defer file.close();
    const writer = file.writer();
    try writer.print("const std = @import(\"std\");\n", .{});
    try writer.print("pub const file_paths = [_][]const u8{{\n", .{});
    try processDirectory("www", &array_list, writer);
    try writer.print("
        \\};

        \\  const EmbeddedFile = struct {
        \\      path: []const u8,
        \\      content: []const u8,
        \\  };

        \\  try embed();

        \\ pub const embedded_files = blk: {
        \\    var fs: [file_paths.len]EmbeddedFile = undefined;
        \\    for (file_paths) |file_path, i| {
        \\        const embedded_file = EmbeddedFile{
        \\            .path = file_path,
        \\            .content = @embedFile(file_path),
        \\        };
        \\        fs[i] = embedded_file;
        \\    }
        \\    break :blk fs;
        \\}};
    ", .{});
}

But got the error:

error: expected expression, found 'invalid bytes'
    try writer.print("
                     ^
<stdin>:37:23: note: invalid byte: '\n'
    try writer.print("
                      ^

Solution

  • Multiline strings don't need the ", they are well-defined by the \\

    Also I would suggest against putting code into the format string of the print method(this would require escaping all the { and }), instead I would suggest to pass it as a separate argument:

        try writer.print("{s}", .{
            \\};
    
            \\  const EmbeddedFile = struct {
            \\      path: []const u8,
            \\      content: []const u8,
            \\  };
    
            \\  try embed();
    
            \\ pub const embedded_files = blk: {
            \\    var fs: [file_paths.len]EmbeddedFile = undefined;
            \\    for (file_paths) |file_path, i| {
            \\        const embedded_file = EmbeddedFile{
            \\            .path = file_path,
            \\            .content = @embedFile(file_path),
            \\        };
            \\        fs[i] = embedded_file;
            \\    }
            \\    break :blk fs;
            \\}};
        });