Push Moves Ownership Into The Vec
push transfers ownership of the whole value into the vector's buffer, the source binding stops existing, and pop hands ownership back out.
Code
#[derive(Debug)]
struct Job {
name: String,
}
fn main() {
let name = String::from("render");
let mut queue: Vec<Job> = Vec::new();
// push moves the whole Job, String field included, into the Vec buffer
queue.push(Job { name });
// println!("{name}"); // would fail: name was moved into the queue
let mut labels = Vec::new();
let label = String::from("urgent");
// push(label) transfers ownership; push(label.clone()) would copy instead
labels.push(label);
println!("queue: {:?}", queue);
println!("labels: {:?}", labels);
// pop hands ownership back out of the Vec
match queue.pop() {
Some(job) => println!("popped {:?}", job),
None => println!("queue empty"),
}
}Walking through the code — Push Moves Ownership Into The Vec
Push Moves Ownership Into The Vec comes down to the function main.
Branching goes through match, whose exhaustiveness checking turns forgotten cases into compile errors.
Watch out for
- All identifiers resolve to built-ins of the language — zero fetching.
Applying it
Signature: fn main()
Output lines are prefixed (queue:, labels:, popped), and each printed line carries the name of its step.
Statements that matter
match queue.pop() {
Some(job) => println!("popped {:?}", job),
None => println!("queue empty"),
}
Interactive Tools for This Topic
FAQ
- What does Push Moves Ownership Into The Vec print when run?
- Running the file directly is enough — expect labeled output lines such as `queue:`, `labels:`, `popped`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.