如何在Zig中向函数传递stream或writer参数?
解决Zig中传递输出流/Writer到函数的错误问题
针对你在Zig 0.10.0中遇到的两个错误,分别给出修复方案:
错误1:'File' is not marked 'pub'
print1函数参数使用的std.io.File并非公开可用类型,而std.io.getStdOut()返回的实际是std.fs.File类型。只需修正参数类型即可:
pub fn print1(file: std.fs.File, str: []const u8) !void { try file.writer().print("{s}", .{str}); }
错误2:expected type 'type', found 'fn(comptime type, comptime type, comptime anytype) type'
std.io.Writer不是具体类型,而是用于构造Writer实例的泛型构造器。要让函数兼容任意符合Writer接口的对象,使用anytype泛型参数是最简洁的方式,Zig会自动推导类型并检查方法兼容性:
fn print2(writer: anytype, str: []const u8) !void { try writer.print("{s}", .{str}); }
若需要更严谨的类型约束,也可以明确指定Writer接口类型:
fn print2(writer: std.io.Writer(@TypeOf(writer.context), writer.Error, writer.write), str: []const u8) !void { try writer.print("{s}", .{str}); }
完整修复代码
const std = @import("std"); pub fn main() !void { try print1(std.io.getStdOut(), "Hello, "); try print2(std.io.getStdOut().writer(), "world!"); } pub fn print1(file: std.fs.File, str: []const u8) !void { try file.writer().print("{s}", .{str}); } fn print2(writer: anytype, str: []const u8) !void { try writer.print("{s}", .{str}); }
内容的提问来源于stack exchange,提问作者Adrian Savage
相关产品推荐
相关产品推荐

