std.io.buffered_writer.BufferedWriter madness

I’m trying to declare a writer in the main and pass it to a struct:

Relevant lines from main:

...
    var buf_writer = std.io.bufferedWriter(std.io.getStdOut().writer());
...
    var the_app = TheApp{
        .name = "Threaded App",
        .is_running = true,
        .heart_beat = false,
        .width = 15,
        .height = 20,
        .writer = &buf_writer,
    };
...

Relevant parts from struct TheApp:

...
const TheApp = struct {
    name: []const u8,
    mutex: std.Thread.Mutex = .{},
    is_running: bool,
    heart_beat: bool,
    width: u8,
    height: u8,
    writer: *std.io.BufferedWriter(4096, std.fs.File.Writer).Writer,
...

The error that I get:

error: expected type '*io.GenericWriter(*io.buffered_writer.BufferedWriter(4096,io.GenericWriter(fs.File,error{DiskQuota,FileTooBig,InputOutput,NoSpaceLeft,DeviceBusy,InvalidArgument,AccessDenied,BrokenPipe,SystemResources,OperationAborted,NotOpenForWriting,LockViolation,WouldBlock,ConnectionResetByPeer,Unexpected},(function 'write'))),error{DiskQuota,FileTooBig,InputOutput,NoSpaceLeft,DeviceBusy,InvalidArgument,AccessDenied,BrokenPipe,SystemResources,OperationAborted,NotOpenForWriting,LockViolation,WouldBlock,ConnectionResetByPeer,Unexpected},(function 'write'))',
found '*io.buffered_writer.BufferedWriter(4096,io.GenericWriter(fs.File,error{DiskQuota,FileTooBig,InputOutput,NoSpaceLeft,DeviceBusy,InvalidArgument,AccessDenied,BrokenPipe,SystemResources,OperationAborted,NotOpenForWriting,LockViolation,WouldBlock,ConnectionResetByPeer,Unexpected},(function 'write')))'

I feel like the writers are a struggle… any pointers how to get this work on zig 0.13.0?

You are storing a pointer to

writer: *std.io.BufferedWriter(4096, std.fs.File.Writer).Writer,

To get that type you will have to call buf_writer.writer() and pass a reference to that, or you should remove the .Writer from the field type.

However, if you want a runtime writer interface you should really use an AnyWriter:

...
writer: std.io.AnyWriter,
...

Then your code would become

var buf_writer = std.io.bufferedWriter(std.io.getStdOut().writer());
var writer = buf_writer.writer();
...
var the_app = TheApp{
    .name = "Threaded App",
    .is_running = true,
    .heart_beat = false,
    .width = 15,
    .height = 20,
    .writer = writer.any(),
};
2 Likes

I thought I tried it already, but I must have misread the error messages.

removing the .Writer worked!