How can I update a mutable slice?

Hi All,
I am facing an error while using slice. Is it possible to modify a slice?

fn test(my_slice: &mut [f32]) {
    let my_local = vec![3f32; my_slice.len()];
    *my_slice = my_slice.iter().zip(my_local).map(|(a,b)| a + b).collect();
}
fn main() {
    let mut my_vec = vec![5f32; 30];
    test(&mut my_vec.as_slice());
}

I am getting below error,

a value of type &mut [f32] cannot be built from an iterator over elements of type f32

So I added,

*my_slice = &mut my_slice.iter().zip(my_local).map(|(a,b)| a + b).collect();

Then I got below error,

a value of type [f32] cannot be built from an iterator over elements of type f32

You can collect into many types, but slice is not one of them. How about modifying the slice directly?

fn test(my_slice: &mut [f32]) {
    let my_local = vec![3f32; my_slice.len()];
    for (a, b) in my_slice.iter_mut().zip(my_local) {
        *a += b;
    }
}
fn main() {
    let mut my_vec = vec![5f32; 30];
    test(&mut my_vec);
}
1 Like

Thanks I was thinking passing a vec is not as efficient as slice. One more question - Is it possible to use par_iter() in the for loop? When I use that I am getting an error

the trait `std::iter::Iterator` is not implemented for `rayon::iter::zip::Zip<rayon::slice::IterMut<'_, f32>, rayon::slice::IterMut<'_, f32>>`

Well, test will receive a slice anyway - a reference to vector can coerce to it.

1 Like

par_iter() does not implement Iterator, but does share a lot of its methods. Something like this might work:

fn test(my_slice: &mut [f32]) {
    let my_local = vec![3f32; my_slice.len()];
    my_slice.par_iter_mut().zip(my_local).for_each(|(a, b)| *a += b);
}
2 Likes

Thanks @tuffy. I am following your method now

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.