我正在尝试从函数
coati
和 tapir
打印格式化字符串。这就是程序的样子:
const bufPrint = @import("std").fmt.bufPrint;
const print = @import("std").debug.print;
const DefaultPrng = @import("std").rand.DefaultPrng;
fn qr(comptime a: []const u8) !void { print("\n{s}\n", .{a}); }
fn qt(comptime a: []const u8) !void { print("\n{s}\n", .{a}); }
fn coati(comptime a: []const u8, b: i32) ![]const u8 {
var buffer: [64]u8 = undefined;
return try bufPrint(&buffer, "{d}: a {s} number.", .{b, a});
}
fn tapir(comptime a: []const u8) ![]const u8 {
var buffer: [64]u8 = undefined;
return try bufPrint(&buffer, "Checked by {s}.", .{a});
}
pub fn main() !void {
const qa = @constCast(&DefaultPrng.init(0)).random().intRangeAtMost(i32, 0, 59);
// const qb = qa / 20;
try qr("Statements.");
if (qa < 20) {
const head = try coati("lesser", qa);
const tail = try tapir("if-else statement");
try print("{s} {s}\n", .{head, tail});
} else if (qa < 40) {
const head = try coati("middle", qa);
const tail = try tapir("if-else statement");
try print("{s} {s}\n", .{head, tail});
} else {
const head = try coati("greater", qa);
const tail = try tapir("if-else statement");
try print("{s} {s}\n", .{head, tail});
}
}
由于某些原因,当我运行它时,第
try print("{s} {s}\n", .{head, tail});
行出现错误,并显示以下消息:
error: expected error union type, found 'void'
try print("{s} {s}\n", .{head, tail});
~~~~~^~~~~~~~~~~~~~~~~~~~~~~~~~~~
referenced by:
callMain: C:\ProgramData\chocolatey\lib\zig\tools\zig-windows-x86_64-0.12.0\lib\std\start.zig:511:32
WinStartup: C:\ProgramData\chocolatey\lib\zig\tools\zig-windows-x86_64-0.12.0\lib\std\start.zig:350:45
remaining reference traces hidden; use '-freference-trace' to see all reference traces
在我看来,
coati
和tapir
中的字符串分配失败,但我不知道我错在哪里。