Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to declare a static array of vectors?

Tags:

rust

How would one go about declaring a static/constant array of variable-sized arrays (vectors) in Rust? In C++ you could do something like this:

static const std::vector<std::string> MY_STRINGS[] = {
    { "hi" },
    { "hello", "world" },
    { "salutations", "watery", "globe" }
};

and things would work as you expect (the array is constructed during app launch afaik). What's the equivalent code in Rust? Seems like the compiler is trying its very best to prevent me from doing this.

like image 632
elskrrrrt Avatar asked Oct 24 '25 04:10

elskrrrrt


2 Answers

Use once_cell::Lazy sync or unsync variants depending on your needs:

const MY_STR: Lazy<[Vec<&str>; 2]> =
    Lazy::new(|| [vec!["hi"], vec!["hello", "world"]]);

Playground

It is still in nightly but this functionality will hit stable at some point. std::lazy::Lazy and std::lazy::SyncLazy.

like image 102
Netwave Avatar answered Oct 26 '25 19:10

Netwave


If you are on nightly, you can use LazyLock. Like this:

#![feature(once_cell)]   // 1.65.0-nightly

use std::sync::LazyLock;

const MY_STRINGS: LazyLock<[Vec<&str>; 3]> =
    LazyLock::new(|| [
        vec!["hi"], 
        vec!["hello", "world"],
        vec!["salutations", "watery", "globe"]
    ]);

fn main() {
    println!("{}, {}", MY_STRINGS[1][0], MY_STRINGS[2][2]);
}

LazyLock more or less does what the crates once_cell and lazy_sync do. Those two crates are very common, so there's a good chance they might already by in your Cargo.lock dependency tree. But if you prefer to be a bit more "adventurous" and go with LazyLock, be prepered that it (as everything in nightly) might be a subject to change before it gets to stable.

(Note: Up until recently std::sync::LazyLock used to be named std::lazy::SyncLazy but was recently renamed.)

like image 38
at54321 Avatar answered Oct 26 '25 20:10

at54321