Search code examples
rustenumsstatic-variables

How to write a collection of static variable in Rust


I want to collect the static variable like java

Class A {
  public static final String HELLO = "hello";
  public static final String WORLD = "world";
}

But it's not supported by enum or struct in Rust! Should I use something like static HashMap?


Solution

  • The most literal and straightforward conversion of this would be "associated constants":

    struct A { /* .. */ }
    
    impl A {
        const HELLO: &str = "hello";
        const WORLD: &str = "world";
    }
    

    which would be accessible via A::HELLO and A::WORLD.


    However, if you don't intend on using A and just wanted it as a scoping mechanism, you should use a module:

    mod constants {
        const HELLO: &str = "hello";
        const WORLD: &str = "world";
    }
    

    which would be accessible via constants::HELLO and constants::WORLD.


    If you wanted this as a static hash map, that would look like this:

    use std::collections::HashMap;
    use once_cell::sync::Lazy; // 1.15.0
    
    static A: Lazy<HashMap<&str, &str>> = Lazy::new(|| {
        let mut map = HashMap::new();
        map.insert("HELLO", "hello");
        map.insert("WORLD", "world");
        map
    });
    

    In Rust, static variables must be initialized with a const expression, but since inserting into a HashMap is not const, we can use Lazy from the once-cell crate to initialize it lazily. This will obviously be different to access since it is not a set of known definitions: A.get("HELLO").unwrap()