Use of array as data structure

⚓ rust    📅 2025-06-03    👤 surdeus    👁️ 2      

surdeus

I am working on a Rust project. One part of it is based on an algorithm originally written in Matlab. In this Matlab code, arrays are used as data structures. All arrays have fixed length, and each element inside the array represents a specific property (i.e., arrays are state vectors, and thus each element is a state variable). I took the easy route, and basically translated the code from Matlab to Rust almost one-to-one. In an extremely simplified way, the Rust code looks something like this:

const X_A: usize = 0;
const X_B: usize = 1;
const X_LEN: usize = 2;

pub fn algorithm(x: &mut [f64; X_LEN], // State vector
) {
    x[X_A] = do_stuff_to_A();
    x[X_B] = do_stuff_to_B();
    do_linear_algebra_stuff(x);
}

In some cases I need access to each element of x, in other cases I want x to behave as a vector (in the linear algebra sense). In the former cases, a structure would make more sense; in the latter, perhaps is best to use an array as done so far. Alternatively, I could use a struct that impl a conversion to an array.

My questions are: is the code above consider bad style or non-idiomatic? More specifically, what are the main disadvantages (if any) of keeping the Rust code like it is? Is there a better way (e.g., using struct, Vec, enum, etc. instead)?

4 posts - 3 participants

Read full topic

🏷️ rust_feed