Replace multiple values in array at the same time

With this code, I can update a single value in an array:

fn main() {
    let mut values = vec![0; 5];
    dbg!(&values);
   {
        let v = &mut values;
        (*v)[2] = 1;
    }
    dbg!(&values);
}

But, it does not work when update two values at the same time:

fn main() {
    let mut values = vec![0; 5];
    dbg!(&values);
    {
        let v = &mut values;
        (*v)[2..4] = [1, 1];
    }
    dbg!(&values);
}

Errors:

error[E0308]: mismatched types
--> src/main.rs:7:22
|
7 |         (*v)[2..4] = [1, 1];
|                      ^^^^^^^^^ expected slice `[{integer}]`, found array `[{integer}; 3]`

error[E0277]: the size for values of type `[{integer}]` cannot be known at compilation time
--> src/main.rs:7:9
|
7 |         (*v)[2..4] = [1, 1];
|         ^^^^^^^^^^ doesn't have a size known at compile-time
|
= help: the trait `Sized` is not implemented for `[{integer}]`
= note: the left-hand-side of an assignment must have a statically known size
error: aborting due to 2 previous errors

How do you update multiple values ?

1 Like

Hello @jnth

Do you mean something like this?

fn main() {
    let mut values = vec![0; 5];
    dbg!(&values);
    {
        let v = &mut values;
        v.splice(2..4,  vec![1, 1]);
    }
    dbg!(&values);
}

Works - but one is using an iter - which means to me, one can do it on one line - but under the hood it replaces one item after the other. Hope it helps.

Stefan

Thank you @sdoerig.

I would do this:

fn main() {
    let mut values = vec![0; 5];
    values[2..4].copy_from_slice(&[1, 1]);
    dbg!(&values);
}

Note: you never need to use an extra block { } to restrict the scope of a borrow like let v = &mut values;. The compiler is smart enough that adding such a block won't make a difference to whether your code compiles. Further, in most cases if foo is a method that takes &mut self, and x is a value of the appropriate type, you can just call x.foo() instead of creating a new binding let v = &mut x; for the mutable borrow.

3 Likes

Thank you @cole-miller for the explaination !

1 Like