pnadeau
pnadeau

Reputation: 603

Rust: How to perform arithmetic on a Vec of items

I've got code to write where there is a common idiom where I have a Vec<f64> and I have to perform some arithmetic on it.

Sometimes I want to modify the Vec in place, and other times I want to create new Vec with the results of the operation.

What is the idiomatic way to do each of these in Rust?

Upvotes: 0

Views: 535

Answers (1)

Finomnis
Finomnis

Reputation: 22446

Modify in place:

fn main() {
    let mut data: Vec<f64> = vec![1.0, 2.0, 3.0, 4.0];

    for el in &mut data {
        *el *= 2.0;
    }

    println!("{:?}", data);
}
[2.0, 4.0, 6.0, 8.0]

Create a new Vec with the results:

fn main() {
    let data: Vec<f64> = vec![1.0, 2.0, 3.0, 4.0];

    let results: Vec<f64> = data.iter().map(|el| el * 2.0).collect();

    println!("Original: {:?}", data);
    println!("Results: {:?}", results);
}
Original: [1.0, 2.0, 3.0, 4.0]
Results: [2.0, 4.0, 6.0, 8.0]

Background

for el in &mut data iterates over data mutably without consuming it. el is a &mut f64 that directly references the item in the vector; modifying it directly modifies the vector content.

data.iter() creates an iterator over the elements of data without consuming data. .map() then applies an operation to each element and returns a new iterator over the results. .collect() then consumes all elements of the iterator and collects it into whatever it's supposed to create; in this case a Vec<f64> due to the type annotation after results. The pattern .iter().map().collect() is fairly common in Rust and is worth being remembered.

Upvotes: 5

Related Questions