0

我在尝试

test "foo" {
    var map = std.StringHashMap(void).init(std.testing.allocator);
    defer {
        while (map.keyIterator().next()) |key| {
            std.testing.allocator.free(key);
        }
        map.deinit();
    }
}

但是出现编译错误

/snap/zig/4365/lib/std/mem.zig:2749:9: error: expected []T or *[_]T, passed *[]const u8
        @compileError("expected []T or *[_]T, passed " ++ @typeName(sliceType));
        ^
/snap/zig/4365/lib/std/mem.zig:2756:59: note: called from here
pub fn sliceAsBytes(slice: anytype) SliceAsBytesReturnType(@TypeOf(slice)) {
                                                          ^
/snap/zig/4365/lib/std/mem.zig:2756:59: note: called from here
pub fn sliceAsBytes(slice: anytype) SliceAsBytesReturnType(@TypeOf(slice)) {
                                                          ^
./main.zig:169:39: note: called from here
            std.testing.allocator.free(key);
                                      ^
./main.zig:165:12: note: called from here
test "foo" {

帮助将不胜感激!如果你遇到同样的情况可以分享,你会在搜索引擎中搜索什么,或者在 zig std 代码库中找到解决方案,也很棒!因为我仍然很难自己找出解决方案。谢谢!

4

1 回答 1

1

键是指向键的指针,因为这个错误说

error: expected []T or *[_]T, passed *[]const u8

要从中获取[]const u8,您必须取消引用它 ( key.*)

test "foo" {
    var map = std.StringHashMap(void).init(std.testing.allocator);
    defer {
        while (map.keyIterator().next()) |key| {
            std.testing.allocator.free(key.*);
        }
        map.deinit();
    }
}
于 2021-12-11T00:06:11.457 回答