实现说明
push 将所有权移交进 Vec的核心是函数 main。
match 把每种情况写明白;漏写一个就编译不过。
使用要点
- 跑完文件,输出里会留下标记——
queue:、labels:、popped。
常见问题
运行「push 将所有权移交进 Vec」会打印什么?
文件本身就是完整程序,直接运行——输出行带有 queue:、labels:、popped 这类标签。
核心语句
match queue.pop() {
Some(job) => println!("popped {:?}", job),
None => println!("queue empty"),
}
代码示例
#[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"),
}
}