Vec Splice Replace Range

Replace a middle range in place with Vec::splice, keep the removed elements, and reuse the same call with an empty iterator to delete.

RustData Integrity

Code

rustsnippet
19 lines
fn main() {
    let mut queue = vec!["a", "b", "c", "d", "e"];

    // splice returns the removed elements and writes the replacement in place
    let removed: Vec<_> = queue.splice(1..3, ["B", "C"]).collect();
    println!("removed: {removed:?}");
    println!("after replace: {queue:?}");

    // an empty replacement deletes the range
    let gone: Vec<_> = queue.splice(1..2, std::iter::empty::<&str>()).collect();
    println!("deleted: {gone:?}");
    println!("after delete: {queue:?}");

    // an empty range inserts without removing anything
    let inserted: Vec<_> = queue.splice(1..1, ["x", "y"]).collect();
    println!("replaced by insert: {inserted:?}");
    println!("after insert: {queue:?}");
    println!("len: {}", queue.len());
}

Inside the snippet

Structurally, expect the function main and nothing else.

Points of care

  • Everything it calls is documented as part of the language core.

Putting it to use

Expect labeled output — removed:, after replace:, deleted: — when the file runs.

Core lines

let gone: Vec<_> = queue.splice(1..2, std::iter::empty::<&str>()).collect();
let inserted: Vec<_> = queue.splice(1..1, ["x", "y"]).collect();
let removed: Vec<_> = queue.splice(1..3, ["B", "C"]).collect();

Interactive Tools for This Topic

FAQ

What does Vec Splice Replace Range print when run?
Invoke the file as-is — the `removed:`, `after replace:`, `deleted:` prefixes identify which step printed each line.