Remove Ranges From Strings With drain
Cut byte ranges out of a String in place with drain, collect the removed part, and keep indices on char boundaries to avoid panics.
Code
fn main() {
let mut note = String::from("[draft] deploy notes v2");
// drain 返回被移除范围的迭代器:collect 出被删内容
let removed: String = note.drain(..8).collect();
println!("removed: {removed}");
println!("left: {note}");
// 尾部范围:去掉末尾的版本号
let cut = note.len() - 3; // 全 ASCII,字节下标即字符下标
note.drain(cut..);
println!("trimmed: {note}");
// 空范围不产生任何变化
note.drain(0..0);
println!("unchanged: {note}");
}Removing and keeping the cut
note.drain(..8) deletes the first 8 bytes and returns them, so removed prints [draft] (with its trailing space) and left prints deploy notes v2 — removal and capture in one call.
Tail trimming
The cut index is note.len() - 3, valid here because the remaining text is all ASCII (byte index = char index); drain(cut..) removes the trailing version marker, printing trimmed: deploy notes.
Boundaries and no-ops
drain(0..0) changes nothing (unchanged line). Rust panics if a range splits a multi-byte character, so non-ASCII strings must locate boundaries via char_indices before draining — the code comment calls this out.
Interactive Tools for This Topic
FAQ
- Why must drain ranges land on char boundaries?
- Strings are UTF-8 byte arrays; a range splitting a multi-byte character would produce invalid text, so Rust panics instead — use char_indices to find safe indices.
- What does drain return?
- An iterator over the removed bytes, which the demo collects into a String to print the removed prefix.
Report a problem with this exampleOpens a pre-filled issue on GitHub.