I cannot initialize a global variable with the stdout in zig:
var out = std.io.getStdOut().writer();
Then I tried to initialize in the fn main
and declare the global variables as optional (initialized by null).
My problem is that I don't know which is the type of std.io.getStdOut().writer();
.
I tried something like:
var out: std.fs.Writer? = null
//...
fn main() !void {
out = std.io.getStdOut().writer();
//...
out.print("ok: {}", "ok");
}
Also I tried reflection:
var stdout: @typeInfo(@TypeOf(std.io.getStdOut().writer())).Fn.return_type.? = null;
I need to know how I can declare a variable or a function returning a Writer (i.e. something that has the usual print function inside).
Tied twice using zig version 0.12.0-dev.1150+3c22cecee and 0.11.0
With writer.zig file containing:
const std = @import("std");
var out = std.io.getStdOut().writer();
pub fn main() anyerror!void {
try out.print("{any}\n", .{@TypeOf(out)});
}
I get error: unable to evaluate comptime expression
zig build-exe writer.zig && writer.exe
C:\bin\zig\lib\std\os\windows.zig:1944:28: error: unable to evaluate comptime expression
break :blk asm volatile (
^~~
C:\bin\zig\lib\std\os\windows.zig:1959:15: note: called from here
return teb().ProcessEnvironmentBlock;
~~~^~
C:\bin\zig\lib\std\io.zig:37:30: note: called from here
return os.windows.peb().ProcessParameters.hStdOutput;
~~~~~~~~~~~~~~^~
C:\bin\zig\lib\std\io.zig:51:34: note: called from here
.handle = getStdOutHandle(),
~~~~~~~~~~~~~~~^~
writer.zig:3:27: note: called from here
var out = std.io.getStdOut().writer();
~~~~~~~~~~~~~~~~^~
referenced by:
main: writer.zig:6:9
callMain: C:\bin\zig\lib\std\start.zig:583:32
remaining reference traces hidden; use '-freference-trace' to see all reference traces
It works for me on a Ubuntu/Linux machine. I assume it is a Windows-specific bug:
% cat test.zig
const std = @import("std");
var out = std.io.getStdOut().writer();
pub fn main() anyerror!void {
try out.print("{any}\n", .{@TypeOf(out)});
}
% zig build-exe test.zig && ./test
io.writer.Writer(fs.file.File,error{AccessDenied,Unexpected,DiskQuota,FileTooBig,InputOutput,NoSpaceLeft,DeviceBusy,InvalidArgument,BrokenPipe,SystemResources,OperationAborted,NotOpenForWriting,LockViolation,WouldBlock,ConnectionResetByPeer},(function 'write'))
The last line gives you the returned type.