Fill A Slice In Place With One Value
slice::fill overwrites every element in place, so reused buffers reset between iterations without reallocating; mutable sub-slices fill partially.
Code
fn main() {
// 预分配缓冲区:一次分配,多轮复用
let mut buf = vec![0u8; 8];
println!("fresh: {buf:?}");
// fill 用一个值原地覆盖全部元素,常用于迭代之间清零
buf.fill(0xFF);
println!("masked: {buf:?}");
// 只填前半段:先拿可变子切片,再对它 fill
let (head, _tail) = buf.split_at_mut(4);
head.fill(0);
println!("half cleared: {buf:?}");
// 结构体切片同样适用:fill 要求 T: Clone
#[derive(Debug, Clone)]
struct Slot {
used: bool,
}
let mut slots = vec![Slot { used: true }; 3];
slots.fill(Slot { used: false });
let flags: Vec<bool> = slots.iter().map(|s| s.used).collect();
println!("slots: {flags:?}");
}How the logic is organized
Fill A Slice In Place With One Value keeps everything in the function main.
Points of care
- Nothing to install — the snippet lives inside the standard library.
Using it
The main signature comes out as: fn main()
The run emits 4 labeled sections — fresh:, masked:, half cleared:, slots: — one per step.
Key statements
let flags: Vec<bool> = slots.iter().map(|s| s.used).collect();
Interactive Tools for This Topic
FAQ
- What does Fill A Slice In Place With One Value print when run?
- Running the file directly is enough — expect labeled output lines such as `fresh:`, `masked:`, `half cleared:`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.