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.
Code
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
SemVer Range CheckerCheck whether a semantic version satisfies an npm-style range such as caret, tilde, comparison sets, wildcards, or hyphen ranges.SRI Hash GeneratorGenerate Subresource Integrity (SRI) hashes from resource content using SHA-256, SHA-384, or SHA-512, and copy a ready-to-use script tag.
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.
Report a problem with this exampleOpens a pre-filled issue on GitHub.