2

I have a Vec<f32> like this:

let mut v: Vec<f32> = Vec::new();
v.push(1.0);
v.push(2.0);
v.push(3.0);

Is there an idiomatic way to replace a portion of the contents with a slice? I have a function like this:

fn replace(&mut v: Vec<f32>, start: usize, vals: &[f32]) {
    // ...
}

In this case, I'd like to replace the values in v with values from vals, starting from the index start of v. If I have the aforementioned Vec, I'd like to do this:

// Before v contains (1.0, 2.0, 3.0)
replace(&v, 0, &[4.0, 5.0]);
// Now v would contain (4.0, 5.0, 3.0)

I guess this could be done by iterating starting from the start index, but is there a more idiomatic Rust way of doing this?

Shepmaster
  • 388,571
  • 95
  • 1,107
  • 1,366
manabreak
  • 5,415
  • 7
  • 39
  • 96
  • 2
    [`Vec::splice`](https://doc.rust-lang.org/std/vec/struct.Vec.html#method.splice) ? – Stefan Nov 12 '17 at 13:19
  • 1
    Specifically: `let mut v = vec![1.0, 2.0, 3.0]; v.splice(0..2, [4.0, 5.0].iter().cloned());` – Shepmaster Nov 12 '17 at 16:59
  • @Shepmaster The duplicate is about _inserting_ multiple elements into a vector, while this question is about _replacing_ multiple elements. Do you really think that's the same question? I don't think so, even though the answers to these questions are similar. – Sven Marnach Nov 13 '17 at 11:29
  • The question is not a duplicate (or at least not a duplicate of the question you linked), even if the answer to the other question happens to cover both use cases. – user4815162342 Nov 13 '17 at 13:24
  • 1
    user4815162342 is correct — the *question* is not an exact duplicate, but the *answer* is. The targeted question is actually a slightly broader interpretation of this question. You've helped out the site by providing a unique set of keywords that will point future visitors to to canonical answer — remember that **duplicates are not a bad thing**! Think of it this way: "how do I add 1 and 1" is not a duplicate of "how do I add 2 and 9", but they'd both be a duplicate of "how do I add two integers"; the equivalent is true here. – Shepmaster Nov 13 '17 at 13:33
  • @Shepmaster Fair enough. – user4815162342 Nov 13 '17 at 15:17

0 Answers0