Ownership Moves Through Stages
Hand one Vec through take-by-value stages with zero clones; after each move the previous binding is dead, and reusing it is a compile-time E0382 error.
Code
fn sanitize(raw: Vec<String>) -> Vec<String> {
// 接管所有权:过滤空行后原样交出
raw.into_iter().filter(|l| !l.trim().is_empty()).collect()
}
fn number(lines: Vec<String>) -> Vec<String> {
lines
.into_iter()
.enumerate()
.map(|(i, l)| format!("{:>3}: {}", i + 1, l))
.collect()
}
fn main() {
let raw = vec![
"first stage".to_string(),
String::new(),
"second stage".to_string(),
];
// ownership moves down the pipeline stages:raw -> sanitize -> number,全程零克隆
let cleaned = sanitize(raw);
let numbered = number(cleaned);
for line in &numbered {
println!("{}", line);
}
// 任何一环把所有权交出去之后,旧绑定即刻失效(编译期拒绝)
// println!("{:?}", raw); // ← 取消注释即 E0382: value borrowed after move
println!("final stage count: {}", numbered.len());
}How it works
The code’s whole job belongs to the functions sanitize, number and main.
Repetition is confined to for line in &numbered — the rest of the file is straight-line.
What to watch for
- The only prerequisite is the language toolchain itself.
Applying it
The main signature reads fn sanitize(raw: Vec<String>) -> Vec<String>
The file announces its steps in the output: final stage count:.
Launch the file; main takes over and steps through sanitize and number.
Statements that matter
raw.into_iter().filter(|l| !l.trim().is_empty()).collect()
}
fn number(lines: Vec<String>) -> Vec<String> {
lines
.into_iter()
.enumerate()
.map(|(i, l)| format!("{:>3}: {}", i + 1, l))
.collect()
}
Interactive Tools for This Topic
FAQ
- What does Ownership Moves Through Stages print when run?
- Run it as a complete program — the output lines carry labels such as `final stage count:`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.