AskOverflow.Dev

AskOverflow.Dev Logo AskOverflow.Dev Logo

AskOverflow.Dev Navigation

  • 主页
  • 系统&网络
  • Ubuntu
  • Unix
  • DBA
  • Computer
  • Coding
  • LangChain

Mobile menu

Close
  • 主页
  • 系统&网络
    • 最新
    • 热门
    • 标签
  • Ubuntu
    • 最新
    • 热门
    • 标签
  • Unix
    • 最新
    • 标签
  • DBA
    • 最新
    • 标签
  • Computer
    • 最新
    • 标签
  • Coding
    • 最新
    • 标签
主页 / user-2703818

tk-noodle's questions

Martin Hope
tk-noodle
Asked: 2024-12-16 18:55:24 +0800 CST

如何确定 Zig 中的 Reader 和 Writer 实例的类型?

  • 5

我正在尝试生成一个结构,该结构包含对 stdin/stdout/stderr 的每个读者和写者的引用

然而,我却无法声明适当的类型。我最简单的代码是:

const std = @import("std");

const IoTrio = struct {
    in: std.io.GenericReader,
    out: std.io.GenericWriter,
    err: std.io.GenericWriter,
};

pub fn giveIo() !IoTrio {
    const stdout = std.io.getStdOut().writer();

    var stdin_bo = std.io.bufferedReader(std.io.getStdIn().reader());
    const stdin = stdin_bo.reader();

    const stderr = std.debug;

    @compileLog(@TypeOf(stdin ));
    @compileLog(@TypeOf(stdout));
    @compileLog(@TypeOf(stderr));

    return IoTrio{
        .in = stdin,
        .out = stdout,
        .err = std.debug,
    };
}

pub fn main() !void {
    _ = giveIo();
}

该结构编译失败:

Produces error:
types.zig:5:15: error: expected type 'type', found 'fn (comptime type, comptime type, comptime anytype) type'
    in: std.io.GenericReader,
         ~~~~~~^~~~~~~~~~~~~~

我看了这个答案,但不幸的是,它并没有真正的帮助——正如答案的作者所指出的那样,输出是复杂的,不容易理解——讨论到此结束。

事实上,输出结果相当令人困惑:

@as(type, io.GenericReader(*io.buffered_reader.BufferedReader(4096,io.GenericReader(fs.File,error{AccessDenied,Unexpected,InputOutput,BrokenPipe,SystemResources,OperationAborted,WouldBlock,ConnectionResetByPeer,IsDir,ConnectionTimedOut,NotOpenForReading,SocketNotConnected},(function 'read'))),error{AccessDenied,Unexpected,InputOutput,BrokenPipe,SystemResources,OperationAborted,WouldBlock,ConnectionResetByPeer,IsDir,ConnectionTimedOut,NotOpenForReading,SocketNotConnected},(function 'read')))

@as(type, io.GenericWriter(fs.File,error{AccessDenied,Unexpected,DiskQuota,FileTooBig,InputOutput,NoSpaceLeft,DeviceBusy,InvalidArgument,BrokenPipe,SystemResources,OperationAborted,NotOpenForWriting,LockViolation,WouldBlock,ConnectionResetByPeer},(function 'write')))

@as(type, type)

这似乎暗示每个都是一个函数?但我无法将这些值插入到我的结构声明中,也不明白这是什么意思,让我猜测一些更合理的内容。

我如何读取这些输出来得出我的结构所需的类型符号?

types
  • 1 个回答
  • 29 Views
Martin Hope
tk-noodle
Asked: 2024-10-10 18:44:02 +0800 CST

process.Child.spawn() 无法编译,并显示“错误:预期的元组或结构参数,发现 []u8”

  • 5

我编写了一个基本的命令调用包装函数,表面上看语法上似乎没问题。它基于Zig Cookbook中的一个示例,确实可以编译和运行。

然而,编译失败并出现一个我无法解决的错误,似乎(但可能并非真正)存在于标准库深处。

代码:

const std = @import("std");
const Child = std.process.Child;

const RunError = error {
    Failed,
};

pub fn callCommand(alloc:std.mem.Allocator, command:[]const[]const u8) !std.ArrayList(u8) {
    var caller = Child.init(command, alloc);
    caller.stdout_behavior = .Pipe;
    caller.stderr_behavior = .Pipe;

    var stdout = std.ArrayList(u8).init(alloc);
    var stderr = std.ArrayList(u8).init(alloc);
    errdefer stdout.deinit();
    defer stderr.deinit();

    try caller.spawn(); // Error points to here...
    try caller.collectOutput(&stdout, &stderr, 1024);

    const res = try caller.wait();

    if(res.Exited > 0) {
        std.debug.print("{s}\n", stderr.items); // EDIT - this is the culprit, however
        return RunError.Failed;
    } else {
        return stdout;
    }
}

test {
    const alloc = std.testing.allocator;
    const out = try callCommand(alloc, &[_][]const u8{"ls", "-l"});
    defer out.deinit();
    std.debug.print("{s}\n", .{out.items});
}

尝试编译时:

$ zig test -freference-trace src/commands.zig
/home/tk-noodle/.local/var/zig/zig-linux-x86_64-0.13.0/lib/std/fmt.zig:88:9: error: expected tuple or struct argument, found []u8
        @compileError("expected tuple or struct argument, found " ++ @typeName(ArgsType));
        ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
referenced by:
    print__anon_5241: /home/tk-noodle/.local/var/zig/zig-linux-x86_64-0.13.0/lib/std/io/Writer.zig:24:26
    print: /home/tk-noodle/.local/var/zig/zig-linux-x86_64-0.13.0/lib/std/io.zig:324:47
    print__anon_6636: /home/tk-noodle/.local/var/zig/zig-linux-x86_64-0.13.0/lib/std/debug.zig:97:21
    unexpectedErrno: /home/tk-noodle/.local/var/zig/zig-linux-x86_64-0.13.0/lib/std/posix.zig:7319:24
    setreuid: /home/tk-noodle/.local/var/zig/zig-linux-x86_64-0.13.0/lib/std/posix.zig:3372:30
    spawnPosix: /home/tk-noodle/.local/var/zig/zig-linux-x86_64-0.13.0/lib/std/process/Child.zig:673:18
    spawn: /home/tk-noodle/.local/var/zig/zig-linux-x86_64-0.13.0/lib/std/process/Child.zig:242:20
    callCommand: src/commands.zig:18:15
    test_0: src/commands.zig:35:21

具体来说,似乎在编译时会到达lib/std/posix.zig:3372:30,从而将错误枚举传递给lib/std/posix.zig:7319:24

通过一些混乱,我确实确认了这.{@intFromEnum(err)}可以解析为struct{u16},但不知何故,这被传递下来,最终导致错误,指出它看到一个[]u8。

它表面上看起来像一个编译器问题,但如果我改变代码以返回!void并简单地丢弃 stdout/stderr ,程序就会顺利编译,并且测试通过。

所以我的问题有两个:

  • 我做错了什么导致这个错误?
  • 为什么错误看起来像是指向 stdlib 中的问题,而不是我自己的代码?
zig
  • 1 个回答
  • 17 Views
Martin Hope
tk-noodle
Asked: 2024-09-28 06:49:59 +0800 CST

无法从任意长度的字符串数组中释放内存字符串

  • 5

我想编写一个函数来读取文本文件,并将其行作为字符串数组返回以供进一步处理。

为此,我试图正确处理长度为 N 的字符串数组,其中 N 在运行时确定。

我有这个基本示例,其中有一个长度为 2 的硬编码数组。它运行良好,并且没有报告任何泄漏:

const std = @import("std");
const stdout = std.io.getStdOut().writer();
var gpa = std.heap.GeneralPurposeAllocator(.{}){};

pub fn main() !void {
    const alloc = gpa.allocator();
    defer _ = gpa.deinit();

    const names = try getNames(alloc);
    defer destroyNames(alloc, names);

    for(names) |name| {
        try stdout.print("Hello {s}\n", .{name});
    }
}


fn destroyNames(alloc:std.mem.Allocator, names:*[2][]const u8) void {
    for(names) |name| {
        // Correctly frees the '[]const u8'
        alloc.free(name);
    }
    _ = alloc.destroy(names);
}


fn getNames(alloc:std.mem.Allocator) !*[2][]const u8 {
    const names = [_][]const u8{"Alix", "Bub"};

    const new_names = try alloc.create([2][]const u8);
    const title = "Prof";

    for(names, 0..) |name, i| {
        new_names[i] = try std.fmt.allocPrint(alloc, "{s} {s}", .{title, name} );
    }

    return new_names;
}

对此感到满意,我继续移动一些东西。下面的代码运行,但在延迟destroyNames操作上失败

const std = @import("std");
const stdout = std.io.getStdOut().writer();
var gpa = std.heap.GeneralPurposeAllocator(.{}){};

pub fn main() !void {
    const alloc = gpa.allocator();
    defer _ = gpa.deinit();

    const names = try getNames(alloc);
    defer destroyNames(alloc, names);

    for(names.*) |name| {
        try stdout.print("Hello {s}\n", .{name});
    }
}


fn destroyNames(alloc:std.mem.Allocator, names:*[][]const u8) void {
    for(names.*) |name| {
        // ERROR - core dumps here...!
        // Cannot properly free a '[]const u8' supplied like this
        alloc.free(name);
    }
    _ = alloc.destroy(names);
}


fn getNames(alloc:std.mem.Allocator) !*[][]const u8 {
    // Stand-in. Hypothetically, read from a N-line file...
    const names = [_][]const u8{"Alix", "Bub"};

    var new_names:[][]const u8 = undefined;
    new_names = try alloc.create([names.len][]const u8);
    const title = "Prof";

    for(names, 0..) |name, i| {
        new_names[i] = try std.fmt.allocPrint(alloc, "{s} {s}", .{title, name} );
    }

    return &new_names;
}

运行结果

$ zig run length-general.zig 
Hello Prof Alix
Hello Prof Bub
General protection exception (no address available)
/home/tai/.local/var/zig/zig-linux-x86_64-0.14.0-dev.1366+d997ddaa1/lib/compiler_rt/memset.zig:19:14: 0x10f7f10 in memset (compiler_rt)
            d[0] = c;
             ^
/home/tai/.local/var/zig/zig-linux-x86_64-0.14.0-dev.1366+d997ddaa1/lib/std/mem/Allocator.zig:313:26: 0x1040e57 in free__anon_3449 (length-general)
    @memset(non_const_ptr[0..bytes_len], undefined);
                         ^
/home/tai/scratch-zig/length-general.zig:26:19: 0x103bacc in destroyNames (length-general)
        alloc.free(name);
                  ^
/home/tai/scratch-zig/length-general.zig:14:23: 0x103b59c in main (length-general)
    defer destroyNames(alloc, names);
                      ^
/home/tai/.local/var/zig/zig-linux-x86_64-0.14.0-dev.1366+d997ddaa1/lib/std/start.zig:615:37: 0x103ad2f in posixCallMainAndExit (length-general)
            const result = root.main() catch |err| {
                                    ^
/home/tai/.local/var/zig/zig-linux-x86_64-0.14.0-dev.1366+d997ddaa1/lib/std/start.zig:250:5: 0x103a90f in _start (length-general)
    asm volatile (switch (native_arch) {
    ^
???:?:?: 0x0 in ??? (???)
Aborted (core dumped)

作为一个尝试检查,我确实尝试alloc.free(name.*)在这两个例子中,并且都报告了相同的error: index syntax required for slice type '[]const u8'结果,这对我来说意味着它们确实都收到了相同的结果[]const u8

我该如何修复这些错误?

arrays
  • 1 个回答
  • 68 Views
Martin Hope
tk-noodle
Asked: 2023-09-09 03:04:54 +0800 CST

在子模块中导入同级模块无法解决

  • 5

我试图了解如何在 Rust 中将代码拆分为多个文件。

执行时cargo run我得到这个:

error[E0432]: unresolved import `super::path`
 --> util/message.rs:1:5
  |
1 | use super::path;
  |     ^^^^^^^^^^^ no `path` in `util`

文件布局和内容如下:

./util/path.rs

pub const PATHFILE_PATH:&str = "~/.PATH";

./util/message.rs

use super::path;

pub fn display_message() {
    println!("{}", path.PATHFILE_PATH);
}

./main.rs

mod util;

fn main() {
    util::message::display_message();
}

./util.rs

pub mod message;

据我所知,我正在做预期的事情。以前的 答案以及这本书似乎都证实我正在做正确的事情,但我失败了。

谁能帮我找出我做错了什么?

完整的布局也在 github 上

rust
  • 2 个回答
  • 30 Views

Sidebar

Stats

  • 问题 205573
  • 回答 270741
  • 最佳答案 135370
  • 用户 68524
  • 热门
  • 回答
  • Marko Smith

    重新格式化数字,在固定位置插入分隔符

    • 6 个回答
  • Marko Smith

    为什么 C++20 概念会导致循环约束错误,而老式的 SFINAE 不会?

    • 2 个回答
  • Marko Smith

    VScode 自动卸载扩展的问题(Material 主题)

    • 2 个回答
  • Marko Smith

    Vue 3:创建时出错“预期标识符但发现‘导入’”[重复]

    • 1 个回答
  • Marko Smith

    具有指定基础类型但没有枚举器的“枚举类”的用途是什么?

    • 1 个回答
  • Marko Smith

    如何修复未手动导入的模块的 MODULE_NOT_FOUND 错误?

    • 6 个回答
  • Marko Smith

    `(表达式,左值) = 右值` 在 C 或 C++ 中是有效的赋值吗?为什么有些编译器会接受/拒绝它?

    • 3 个回答
  • Marko Smith

    在 C++ 中,一个不执行任何操作的空程序需要 204KB 的堆,但在 C 中则不需要

    • 1 个回答
  • Marko Smith

    PowerBI 目前与 BigQuery 不兼容:Simba 驱动程序与 Windows 更新有关

    • 2 个回答
  • Marko Smith

    AdMob:MobileAds.initialize() - 对于某些设备,“java.lang.Integer 无法转换为 java.lang.String”

    • 1 个回答
  • Martin Hope
    Fantastic Mr Fox msvc std::vector 实现中仅不接受可复制类型 2025-04-23 06:40:49 +0800 CST
  • Martin Hope
    Howard Hinnant 使用 chrono 查找下一个工作日 2025-04-21 08:30:25 +0800 CST
  • Martin Hope
    Fedor 构造函数的成员初始化程序可以包含另一个成员的初始化吗? 2025-04-15 01:01:44 +0800 CST
  • Martin Hope
    Petr Filipský 为什么 C++20 概念会导致循环约束错误,而老式的 SFINAE 不会? 2025-03-23 21:39:40 +0800 CST
  • Martin Hope
    Catskul C++20 是否进行了更改,允许从已知绑定数组“type(&)[N]”转换为未知绑定数组“type(&)[]”? 2025-03-04 06:57:53 +0800 CST
  • Martin Hope
    Stefan Pochmann 为什么 {2,3,10} 和 {x,3,10} (x=2) 的顺序不同? 2025-01-13 23:24:07 +0800 CST
  • Martin Hope
    Chad Feller 在 5.2 版中,bash 条件语句中的 [[ .. ]] 中的分号现在是可选的吗? 2024-10-21 05:50:33 +0800 CST
  • Martin Hope
    Wrench 为什么双破折号 (--) 会导致此 MariaDB 子句评估为 true? 2024-05-05 13:37:20 +0800 CST
  • Martin Hope
    Waket Zheng 为什么 `dict(id=1, **{'id': 2})` 有时会引发 `KeyError: 'id'` 而不是 TypeError? 2024-05-04 14:19:19 +0800 CST
  • Martin Hope
    user924 AdMob:MobileAds.initialize() - 对于某些设备,“java.lang.Integer 无法转换为 java.lang.String” 2024-03-20 03:12:31 +0800 CST

热门标签

python javascript c++ c# java typescript sql reactjs html

Explore

  • 主页
  • 问题
    • 最新
    • 热门
  • 标签
  • 帮助

Footer

AskOverflow.Dev

关于我们

  • 关于我们
  • 联系我们

Legal Stuff

  • Privacy Policy

Language

  • Pt
  • Server
  • Unix

© 2023 AskOverflow.DEV All Rights Reserve