pub inline fn getStdout(io: std.Io, comptime buf_size: usize) *std.Io.Writer {
var buf: [buf_size]u8 = undefined;
var instance = std.Io.File.stdout().writer(io, &buf);
return &instance.interface;
}
pub fn main(init: std.process.Init) !void {
const stdout = getStdout(init.io, 4096);
try stdout.writeAll("Hello, World!\n");
try stdout.flush();
}
Is this undefined behaviour? I know returning references to local variables is illegal, but does inlining it make it safe?
It doesn’t. I mean it does for now but that’s not intended. Even blocks can have their stack overwritten.
it is not supposed to be legal, but the current implementation does allow it.
You should not rely on that as it will change, local variables are intended to be confined to their scope, whether that is a function or block, inline functions are no exception.
a function to save 3 lines of code, that also does not provide any additional clarity, is not idiomatic.
Not to mention, the caller may want instance as it provides additional, file specific, functionality e.g seeking, or resizeing the file.
There is the caveat that in comptime it is allowed as values are reference counted.
1 Like