Search code examples
zig

Why does zig function not accept null as function argument when type signature specifies parameter as nullable?


This is my zig code. I am just trying to read a file line by line

pub fn main() anyerror!void {
    const path = "/home/testdata/testfile";
    var f = try fs.openFileAbsolute(path, .{.mode = fs.File.OpenMode.read_only});
    defer f.close();
    debug.print("{any}\n", .{f});
    debug.print("{any}\n", .{fs.cwd()});

    var reader = f.reader();
    var output: [500]u8 = undefined;
    var output_fbs = std.io.fixedBufferStream(&output);
    const writer = output_fbs.writer();
    while(true) {
        reader.streamUntilDelimiter(writer, "\n", null) catch |err| {
            debug.print("{any}\n", .{err});
            break;
        };

        var b = output_fbs.getWritten();
        debug.print("{any}\n", .{b});
    }
}

Now this fails to build with this unhelpful error message saying

main.zig:35:51: error: expected type 'u8', found '*const [1:0]u8'
        reader.streamUntilDelimiter(writer, "\n", null) catch |err| {

But the signature of steamUntilDelimiter is as follows streamUntilDelimiter(self: Self, writer: anytype, delimiter: u8, optional_max_size: ?usize) (...)

If optional_max_size can be null then why won't it accept null as an argument and why does the error message say that I have provided a *const [1:0]u8 is it casting the null into that?

I even tried it with a number instead of null but i get the same error

main.zig:35:51: error: expected type 'u8', found '*const [1:0]u8'
        reader.streamUntilDelimiter(writer, "\n", 100) catch |err| {
                                                  ^~~

Solution

  • please read error carefully. it points to the second argument ("\n"), which accepts a u8 (character) not []const u8 (string). you can write the character inside single quotes ('\n')