Search code examples
arraysstringruststaticallocation

Statically allocate array with struct containing a string


I am writing a program that has an array which size I know, it is a fixed instruction set. Each entry in the array maps to an struct of the opcode and some metadata, such as the function that implements the opcode and its name, a String.

I need to allocate the array before I actually compute and fill the instruction set on each opcode.

Rust won't let me allocate such array statically, even if I know the size and when the initialized state does NOT require ANY pointers, as I would like all strings to be empty, which means no allocations and you could have a "zero value" of the string that is preferably fine to be copied.

Any suggestions? Is there anyway to do it? Seems Rust really likes to you use a Vec for everything? Even when static memory, which should be preferable on a non GC program language, would have been possible in many cases such as this? This is confusing.


Solution

  • From the rust reference:

    If the length operand has a value greater than 1 then this requires that the type of the repeat operand is Copy or that it must be a path to a constant item.

    Therefore, to initialize an array using [VALUE; NUM] syntax, either the type implements the Copy trait or that VALUE is a const.

    As pointed out by Chayim Friedman, you can use code like below:

    const EMPTY: Instruction = Instruction { name: String::new() };
    static ARRAY: [Instruction; 5] = [EMPTY; 5];
    

    However, if you are working with a fixed set of data, it might be easier to just populate the list with predefined names, using &'static str.

    If there is a need to create an array from a value that cannot be made to a constant and is not Copy, you can use std::array::from_fn like so:

    let value = String::new();
    let array: [_; 6] = std::array::from_fn(|_| value.clone());