打印从函数返回的格式化字符串会导致错误“错误:预期错误联合类型,发现'void'”

问题描述 投票:0回答:1

我正在尝试从函数

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
中的字符串分配失败,但我不知道我错在哪里。

zig
1个回答
0
投票

首先,编译器告诉您

print
不会返回错误,因此您不需要在结果上使用
try

其次,字符串确实“分配失败”。您犯了一个典型的新手错误,即返回指向局部变量的指针,这是未定义的行为。有很多其他问题有同样的问题。

© www.soinside.com 2019 - 2024. All rights reserved.