3

Take for example the Rust library lazy_static's example:

use lazy_static::lazy_static;
use std::collections::HashMap;

lazy_static! {
    static ref HASHMAP: HashMap<u32, &'static str> = {
        let mut m = HashMap::new();
        m.insert(0, "foo");
        m.insert(1, "bar");
        m.insert(2, "baz");
        m
    };
    static ref COUNT: usize = HASHMAP.len();
    static ref NUMBER: u32 = times_two(21);
}

How might this be done in Zig?

I have tried this which is the only thing that makes sense to me:

const std = @import("std");

pub fn main() void {
    comptime var h = std.StringHashMap(i32).init(std.testing.allocator);
    h.put("hi", 5) catch {};
    std.debug.print("{}", .{h});
}

but this segfaults.

Is it even possible to do this in Zig?

1
  • In the future, it will eventually be possible to create a normal StringHashMap at comptime using a comptime allocator, but in the current version of zig this would be extremely slow and crashes the compiler. Commented Jul 14, 2022 at 4:50

1 Answer 1

2

Since zig 0.13.0

With zig 0.13.0, the previously known std.ComptimeStringMap was renamed in commit 8af59d1 to std.StaticStringMap, and now lives here in the standard library.

Until zig 0.12.1

It seems (thanks to this Reddit post) that this is implemented in the standard library

and can be used via std.ComptimeStringMap

This however does not seem to support any dynamic insertion as there is no insert method.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.