How can we initialize a BigDecimal array in Rust?

Viewed 110

I wanted to have an array of BigDecimal values, as I know the size ahead of time and it is constant.

I cannot figure out how it could be initialized in Rust however. This method:

#[derive(Debug)]
struct BigArray { values: [BigDecimal; 52] }
fn main() {
    let mut v = BigArray { values: [BigDecimal::from_str("0"); 52] };
    println!("{:?}", v);
}

yields the following error:

the trait Copy is not implemented for BigDecimal

note: the Copy trait is required because the repeated element will be copied

I do want the default BigDecimal value to be cloned across the array.

Is it impossible to do? Is Vec the only option?

I can turn it into a borrowed value but then it is no longer a BigDecimal array, and lifetime management and dangling pointers become quite hairy.

Rust playground snippet.

1 Answers

You can dynamically create a vec and then transform it into the array:

// --- Fake BigDecimal library for testing purposes.
#[derive(Clone, Debug)]
struct BigDecimal {
    str: String,
}
impl BigDecimal {
    fn from_str(str: &str) -> BigDecimal {
        BigDecimal {
            str: String::from(str),
        }
    }
}

// --- Code that is actually under test.
#[derive(Debug)]
struct BigArray {
    values: [BigDecimal; 10],
}
fn main() {
    let mut v = BigArray {
        values: (0..10)
            .map(|_| BigDecimal::from_str("0"))
            .collect::<Vec<_>>()
            .try_into()
            .unwrap(),
    };
    println!("{:?}", v);
}

Playground

Or using map:

fn main() {
    let mut v = BigArray {
        values: [(); 10].map(|_| BigDecimal::from_str("0"))
    };
    println!("{:?}", v);
}

Playground

Related