实现说明
VecDeque Make Contiguous 连续切片的核心是函数 main。
这个示例中仅有的重复出现在 for value in 1..=5 里。
使用要点
- 直接运行文件,输出会带上标签,比如
front、split:、contiguous:——输出的每一行都能指回产生它的那次调用。
常见问题
运行「VecDeque Make Contiguous 连续切片」会打印什么?
不用做任何设置,直接把文件跑完——输出里的 front、split:、contiguous: 标签标明各步骤。
核心语句
let mut queue: VecDeque<i32> = VecDeque::new();
let (front, back) = queue.as_slices();
let slice = queue.make_contiguous();
代码示例
use std::collections::VecDeque;
fn main() {
let mut queue: VecDeque<i32> = VecDeque::new();
for value in 1..=5 {
queue.push_back(value);
}
for _ in 0..3 {
queue.pop_front();
}
for value in 6..=8 {
queue.push_back(value);
}
// the ring buffer is split because the head advanced
let (front, back) = queue.as_slices();
println!("front {front:?} back {back:?}");
println!("split: {}", !front.is_empty() && !back.is_empty());
// make_contiguous rotates the ring into a single slice
let slice = queue.make_contiguous();
println!("contiguous: {slice:?}");
println!("len: {}", queue.len());
// further pushes keep working after the rotation
queue.push_back(9);
println!("after push: {:?}", queue.make_contiguous());
}