Dave Mason
Dave Mason

Reputation: 901

How can I set string values in a static mut array/vec?

I have a symbol table that I want to be static because it is accessed in a lot of circumstances where I don't have a good way to pass the value in. It is a struct and a table that looks like:

struct Symbol {
   string: &'static str,
   other_values: ...,
}
const NO_SYMBOL = Symbol{ string: "", other...};
static mut symbol_table : [Symbol;100] = [NO_SYMBOL;100];

How do I update the string field? It has to be static, because it's in a static array, but I want to generate values (among other things, by reading from a file), so how can I make a String static so I can store it in an element of the array?

Upvotes: 0

Views: 589

Answers (1)

Aiden4
Aiden4

Reputation: 2664

There are a couple of ways to do this, depending on what you think is best. Use a Vec:

static mut symbol_table_1:Vec<Symbol> = Vec:new(); //doesn't actually allocate so is a const fn

or use an option and replace the none values:

static mut symbol_table_2:[Option<Symbol>;100] = [None;100];

unsafe{
    symbol_table_2[0].replace(Some(value));
}

A &'static str can be obtained by using String::into_boxed_str and Box::leak. However, I would highly encourage you to use lazy_static and an RwLock, which enables many readers or one writer to maintain a lock on the static and prevent data races.

lazy_static!{
    static ref symbol_table_3:Rwlock<Vec<Symbol>> = RwLock::new(Vec::new());
}

Full playground link

Upvotes: 1

Related Questions