You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.15 03:15:57