Search code examples
zig

How to pass the `writer` between functions


I wnat to generate a file as below:

const std = @import("std");
const comptime_file_paths = [_][]const u8{
    "www/file1.txt",
    "www/file2.txt",
// ...
};

So I wrote the below code:

const std = @import("std");
const fs = std.fs;
const io = std.io;
const mem = std.mem;

pub fn processDirectory(path: []const u8, array_list: *std.ArrayList([]const u8), writer: std.io.Writer) !void {
    var dir = try fs.cwd().openIterableDir(path, .{});
    defer dir.close();
    var it = dir.iterate();
    while (try it.next()) |entry| {
        var entry_path_buf: [256]u8 = undefined;
        const entry_path = try std.fmt.bufPrint(&entry_path_buf, "{s}/{s}", .{ path, entry.name });
        switch (entry.kind) {
            .File => {
                std.log.info("path: {s}", .{entry_path});
                try writer.print("\"{s}\",\n", .{entry_path});
                try array_list.append(entry_path);
            },
            .Directory => {
                try processDirectory(entry_path, array_list, writer);
            },
            else => {},
        }
    }
}

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("const comptime_file_paths = [_][]const u8{\n", .{});
    try processDirectory("www", &array_list, writer);
    try writer.print("};\n", .{});
}

but it looks I have an issue passing the writer and got the below error:

❯ zig run e05.zig
e05.zig:6:83: error: expected type 'type', found 'fn(comptime type, comptime type, comptime anytype) type'
pub fn processDirectory(path: []const u8, array_list: *std.ArrayList([]const u8), writer: std.io.Writer) !void {
                                                                                  ^~~~~~
referenced by:
    main: e05.zig:37:9
    callMain: /usr/lib/zig/std/start.zig:614:32
    remaining reference traces hidden; use '-freference-trace' to see all reference traces

/usr/lib/zig/std/fmt.zig:143:13: error: missing closing }
            @compileError("missing closing }");
            ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

Solution

  • zig lacks interfaces. so generic types like std.io.Writer cannot be written like that. the only solution at the moment is changing it too anytype

    fn processDirectory(path: []const u8, array_list: *std.ArrayList([]const u8), writer: anytype) !void {