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
    • 最新
    • 标签
主页 / coding / 问题

问题[zig](coding)

Martin Hope
João Areias
Asked: 2025-02-07 20:15:36 +0800 CST

Zig 预期类型 '[]usize',但发现 'type'

  • 6

我正在尝试使用网站https://exercism.org/学习 Zig 。我正在解决这个练习,它要求我们找到第 n 个素数。

我的想法是在需要的时候生成所有这些comptime并返回;这是我当前的代码:

const std = @import("std");
const mem = std.mem;

fn sieve(buffer: []usize, comptime limit: usize) []usize {
    if (limit < 2)
        return buffer[0..0];
    const sqrt_limit = std.math.sqrt(limit);
    var bitset = std.StaticBitSet(limit + 1).initFull();
    var n: usize = 3;
    var i: usize = 1;
    
    
    buffer[0] = 2;
    while(n <= sqrt_limit): (n += 2) {
        if (!bitset.isSet(n))
            continue;

        buffer[i] = n;
        i += 1;
        var j = 2 * n;
        while (j <= limit): (j += i) {
            bitset.unset(j);
        }
    }
    while (n <= limit) : (n += 2) {
        if (!bitset.isSet(i))
            continue;

        buffer[i] = n;
        i += 1;
    }
    return buffer[0..i];
}

const buffer_size = std.math.maxInt(usize);
const primes_buffer = [buffer_size]usize;
const primes = sieve(primes_buffer, buffer_size - 1);

pub fn prime(allocator: mem.Allocator, number: usize) !usize {
    _ = allocator;
    return primes[number-1];
}

但是当我尝试编译它时,出现以下错误:

nth_prime.zig:37:22: error: expected type '[]usize', found 'type'
nth_prime.zig:4:18: note: parameter type declared here

我不明白为什么这里primes_buffer的类型是type;它不应该是吗[]usize?

zig
  • 1 个回答
  • 36 Views
Martin Hope
Ladislus
Asked: 2024-12-29 02:58:44 +0800 CST

Deinit 全局和静态局部变量

  • 7

我在 Zig(使用 v0.13.0)的内存管理方面遇到了麻烦,涉及全局和静态局部变量的去初始化。

我编写了以下程序,但内存泄漏,因此在为GeneralPurposeAllocator启用安全性时程序会出现混乱。我已阅读文档,尤其是有关静态局部变量的部分,但它没有提及(或者它在另一个部分,我错过了)有关如何取消初始化内存的任何内容。

const std = @import("std");

const key_t = u32;
const value_t = u128;
const computed_map_t = std.AutoHashMap(key_t, value_t);

var default_gpa: std.heap.GeneralPurposeAllocator(.{}) = undefined;
const default_allocator = default_gpa.allocator();

pub fn fibonacci(value: key_t) value_t {
    const _state = struct {
        // How do I deinit this map on program end ?
        // Or is it possible to mark it as "ok to leak" ?
        var previously_computed = computed_map_t.init(default_allocator);
    };

    if (value == 0) return 0;
    if (value == 1 or value == 2) return 1;

    // Fallback "dumb" implementation because HashMap cannot be used in comptime
    if (@inComptime()) {
        return fibonacci(value - 2) + fibonacci(value - 1);
    } else {
        if (_state.previously_computed.get(value)) |res| {
            return res;
        } else {
            const res = fibonacci(value - 2) + fibonacci(value - 1);
            _state.previously_computed.put(value, res) catch {
                @panic("Something went wrong");
            };
            return res;
        }
    }
}

pub fn main() !void {
    default_gpa = @TypeOf(default_gpa){};
    defer {
        if (.leak == default_gpa.deinit()) {
            @panic("GPA leaked !");
        }
    }

    const value = 5;
    const result = fibonacci(value);
    std.debug.print("fibonacci({d}) = {d}\n", .{ value, result });
}

我曾考虑过在主函数中初始化映射并将其fibonacci作为指针传递给该函数,但是这有点违背了要点(这个映射只在函数中有用,所以我想将这个变量的范围限制在函数范围内)。

我是不是漏掉了什么?或者,你有什么“窍门”能让你以干净的方式实现这一点吗?

zig
  • 1 个回答
  • 38 Views
Martin Hope
financial_physician
Asked: 2024-12-17 14:01:35 +0800 CST

错误:类型捕获包含对 comptime var 的引用

  • 5

我是 Zig 的新手,正在尝试类型系统。我有一段代码执行一些 comptime 操作来确定张量的形状。我想使用这个 comptime 变量进行一些静态类型分析,并将其保留(目前)作为有用的运行时信息。我收到了错误:error: type capture contains reference to comptime var我试图通过制作我认为它所说的较小版本来重现它,但尝试失败了。

我相信我收到的错误与这篇文章有关,其中的建议是:To fix the error, copy your finalized array to a const before taking a pointer.

我认为我的comptime_shape是一个 const。我可以使用一些帮助来理解我上下文中的这个错误以及如何修复它:

const std = @import("std");

pub fn Tensor(comptime data: anytype) type {
    const comptime_shape = getShape(@TypeOf(data));

    return struct {
        data: @TypeOf(data),
        shape: [comptime_shape.len]usize,

        const Self = @This();
        pub fn init() Self {
            return Self{ .data = data, .shape = comptime_shape };
        }
    };
}

fn getShape(comptime T: type) []const usize {
    const info = @typeInfo(T);
    switch (info) {
        .Array => |arr| {
            if (@typeInfo(arr.child) == .Array) {
                const child_shape = getShape(arr.child);
                var result: [child_shape.len + 1]usize = undefined;
                result[0] = arr.len;
                @memcpy(result[1..], child_shape);
                return &result;
            } else {
                return &[_]usize{arr.len};
            }
        },
        else => @compileError("Invalid tensor type"),
    }
}

test "init tensor" {
    const data: [2][3]f32 = .{ .{ 1, 2, 3 }, .{ 2, 3, 4 } };
    const result = Tensor(data).init();
    std.debug.print("tensor [{}]\n", .{result});
    std.debug.print("tensor.shape [{}]\n", .{result.shape});
}
main.zig:6:12: error: type capture contains reference to comptime var
main.zig:37:26: note: called from here

对我来说这也非常有趣,如果我删除 const 数据的类型提示,那么我会收到一个全新的错误:

test "init tensor" {
    const data = .{ .{ 1, 2, 3 }, .{ 2, 3, 4 } };
    const result = Tensor(data).init();
    std.debug.print("tensor [{}]\n", .{result});
    std.debug.print("tensor.shape [{}]\n", .{result.shape});
}
main.zig:31:17: error: Invalid tensor type
main.zig:4:36: note: called from here
main.zig:37:26: note: called from here
zig
  • 1 个回答
  • 30 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
user8253548
Asked: 2024-10-10 09:40:15 +0800 CST

使用 Zig comptime 生成结构字段名称时出错

  • 5

我正在尝试编写一个使用 comptime 生成结构字段名称的 Zig 程序,但是在构建项目时遇到错误。

Zig 版本:0.13.0

下面是我的代码:

const std = @import("std");

var person_field_names = generateFieldNames(Person);

fn generateFieldNames(comptime T: type) []const []const u8 {
    comptime {
        const typeInfo = @typeInfo(T);
        switch (typeInfo) {
            .Struct => |structInfo| {
                const field_count = structInfo.fields.len;
                var field_names: [field_count][]const u8 = undefined;

                var i: usize = 0;
                while (i < field_count) : (i += 1) {
                    const field = structInfo.fields[i];
                    field_names[i] = field.name;
                }
                return &field_names;
            },
            else => @compileError("Only structs are supported!"),
        }
    }
}

const Person = struct {
    name: []const u8,
    age: u8,
};

pub fn main() void {
    for (person_field_names) |name| {
        std.debug.print("Field name: {s}\n", .{name});
    }
}

当我运行 zig build run 时,出现以下错误:

$ zig build run
run
└─ run comptime_test
   └─ zig build-exe comptime_test Debug native failure
error: the following command exited with error code 3:
C:\softs\zig\zig.exe build-exe -ODebug -Mroot=C:\workspace\zig\comptime_test\src\main.zig --cache-dir C:\workspace\zig\comptime_test\zig-cache --global-cache-dir C:\Users\myhfs\AppData\Local\zig --name comptime_test --listen=-
Build Summary: 0/5 steps succeeded; 1 failed (disable with --summary none)
run transitive failure
└─ run comptime_test transitive failure
   ├─ zig build-exe comptime_test Debug native failure
   └─ install transitive failure
      └─ install comptime_test transitive failure
         └─ zig build-exe comptime_test Debug native (reused)
error: the following build command failed with exit code 1:
C:\workspace\zig\comptime_test\zig-cache\o\9c79a56d0821539e91985b5f4384125d\build.exe C:\softs\zig\zig.exe C:\workspace\zig\comptime_test C:\workspace\zig\comptime_test\zig-cache C:\Users\myhfs\AppData\Local\zig --seed 0xcf452477 -Z3cc02acbdb7abbe2 run

是什么原因导致了此错误?我该如何修复它?

错误代码似乎与我处理字段名称数组的方式有关。我相信问题出在 comptime 处理或从函数返回字段名称上。

zig
  • 1 个回答
  • 19 Views
Martin Hope
Philip Adler
Asked: 2024-08-21 00:27:12 +0800 CST

在 Zig 中,结构体上的字段被视为 Const

  • 5

作为一个学习练习,我正在尝试通过在 std 库中的哈希图上构建来在 zig 中创建一个集合类型。

fn Set(comptime T: type) type {
        return struct {
                hashMap : hashMapType,
                const hashMapType: type = std.hash_map.AutoHashMap(T, T);
                const Self = @This();
                fn init(allocator: std.mem.Allocator) Self {
                        return Self{
                                .hashMap = hashMapType.init(allocator),
                        };
                }
                fn put(self: Self, element: T) std.mem.Allocator.Error!void {
                        return try self.hashMap.put(element, element);
                }
                fn count(self: Self) hashMapType.Size {
                        return self.hashMap.count();
                }
        };
}

当我尝试编译使用该put函数的代码时,收到错误消息:

error: expected type '*hash_map.HashMap(set_experiment.rootPair,set_experiment.rootPair,hash_map.AutoContext(set_experiment.rootPair),80)', found '*const hash_map.HashMap(set_experiment.rootPair,set_experiment.rootPair,hash_map.AutoContext(set_experiment.rootPair),80)'
   return try self.hashMap.put(element, element);
              ~~~~~~~~~~~~^~~~
set_experiment.zig:26:27: note: cast discards const qualifier
/usr/lib/zig/std/hash_map.zig:551:26: note: parameter type declared here
        pub fn put(self: *Self, key: K, value: V) Allocator.Error!void {
                         ^~~~~

显然,我可以看到它抱怨是因为内部哈希图被假定为 const。我无法弄清楚从语法和惯用性上来说正确的修复方法是什么。

zig
  • 1 个回答
  • 23 Views
Martin Hope
Dirk Geurs
Asked: 2024-08-07 20:08:35 +0800 CST

@bitCast 仅接受一个参数,而文档列出了两个

  • 5

我正在尝试将 转换u8为打包结构。Builtin 函数@bitCast似乎是完成这项工作的工具。

根据文档,它应该让我改变类型但保持位表示。

我还在博客文章中找到了一个我想要实现的示例。

const std = @import("std");
const print = std.debug.print;

const mystruct  = packed struct {
    a : u16,
    b : u16,
};

pub fn main() void {
    const s2  :mystruct =   .{ .a = 10, .b = 20};
    const s3 : u32 = @bitCast(u32, s2);
    const s4 : mystruct = @bitCast(mystruct, s3);
    print("{}\n", .{ s4});
}

然而,无论我尝试什么,编译器总是告诉我@bitCast 只接受一个参数,而上面的示例和文档明确列出它需要两个参数。

例如,运行上述代码时,编译器告诉我:

src/main.zig:90:22: error: expected 1 argument, found 2
    const s3 : u32 = @bitCast(u32, s2);
                     ^~~~~~~~~~~~~~~~~

我做错了什么?对我来说,@bitCast 需要两个参数是完全合理的。

我正在使用 Zig 0.13.0。

zig
  • 1 个回答
  • 19 Views
Martin Hope
Veljko Miletic
Asked: 2024-08-05 17:46:43 +0800 CST

为 zig build-exe 指定输出目录和二进制名称

  • 6

cc <srcs> -o <path/and/binary/name>我努力在 的文档中寻找任何与 C 编译器等效的东西zig build-exe。我唯一找到的是选项--name,但它不能指定路径,只能指定单元名称。
有没有办法在命令中这样做,或者使用build.zig文件是唯一的方法?

zig
  • 1 个回答
  • 29 Views
Martin Hope
P H Kaznowski
Asked: 2024-08-05 07:08:14 +0800 CST

为什么 Zig 中的 const 指针与 var 指针不同

  • 5

我在 Zig 中有以下内容

 const std = @import("std");

 var messages = [2]*[]u8{undefined, undefined};

 pub fn main() !void {
     // Allocate some strings
     const msg1 = "First message";
     const msg2 = "Second message has different length";
     const allocator = std.heap.page_allocator;
     const msg1_ptr = try allocator.alloc(u8, msg1.len);
     defer allocator.free(msg1_ptr);
     const msg2_ptr = try allocator.alloc(u8, msg2.len);
     defer allocator.free(msg2_ptr);
     messages[0] = @as(*[]u8, &msg1_ptr);
     messages[1] = @as(*[]u8, &msg2_ptr);

它给出了以下错误

src/main.zig:14:30: error: expected type '*[]u8', found '*const []u8'
    messages[0] = @as(*[]u8, &msg1_ptr);
                             ^~~~~~~~~
src/main.zig:14:30: note: cast discards const qualifier
referenced by:
    callMain: /usr/local/Cellar/zig/0.13.0/lib/zig/std/start.zig:524:32
    callMainWithArgs: /usr/local/Cellar/zig/0.13.0/lib/zig/std/start.zig:482:12
    remaining reference traces hidden; use '-freference-trace' to see all reference traces

为了解决这个问题,只需将指针的 const 改为 var 即可

     var msg1_ptr = try allocator.alloc(u8, msg1.len);
     defer allocator.free(msg1_ptr);
     var msg2_ptr = try allocator.alloc(u8, msg2.len);
     defer allocator.free(msg2_ptr);

为什么 const 指针不能强制转换为 const 无关的指针,但将其更改为 var 是有效的?是不是因为 const 意味着不可变,而 var 则不然,所以限制较少?这是否意味着 const 指针永远不能被强制转换?

zig
  • 1 个回答
  • 34 Views
Martin Hope
Palash Nigam
Asked: 2024-07-27 21:04:44 +0800 CST

有没有办法在 zig 中编写存根函数?

  • 4

就像 Rust 提供的方式todo!()或 Ocaml 提供的方式一样let func = "Failure "Unimplemented"",是否有办法在 zig 中编写一个没有实现主体的函数,并且在编译后不会引发任何警告和错误?

现在我只是用打印来写它,例如

pub fn do_something(self: *MyType) void {
        std.debug.print("TODO %d", self.field);
}
zig
  • 1 个回答
  • 19 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