I was trying
test "foo" {
var map = std.StringHashMap(void).init(std.testing.allocator);
defer {
while (map.keyIterator().next()) |key| {
std.testing.allocator.free(key);
}
map.deinit();
}
}
But got compile error
/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" {
Help would be appreciated! If you could share if you face the same situation, what would you search in the search engine, or find in the zig std code base to figure out the solution, would be great too! As I still have a hard time to figure out solution myself. Thank you!
Key is a pointer to the key as this error says
error: expected []T or *[_]T, passed *[]const u8
To get the []const u8
from it, you have to dereference it (key.*
)
It is also not possible to call next()
on map.keyIterator()
like that, because if not assigned to a variable, the iterator will be const and cannot be mutated (which is necessary). So all you have to do is assign it with var
.
test "foo" {
var map = std.StringHashMap(void).init(std.testing.allocator);
defer {
var keyIter = map.keyIterator();
while (keyIter.next()) |key| {
std.testing.allocator.free(key.*);
}
map.deinit();
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With