实现说明
用 copy_within 做重叠区间拷贝可以归结为函数 main。
使用要点
- 每一步打印都带着自己的标签:
after overlap copy:、moved tail:、shifted:。
常见问题
运行「用 copy_within 做重叠区间拷贝」会打印什么?
运行文件本身,after overlap copy:、moved tail:、shifted: 这些前缀各对应一段演示逻辑。
核心语句
bytes[..4].copy_from_slice(&[1, 2, 3, 4]);
let mut label = *b"abcdefgh";
bytes.copy_within(0..4, 2);
代码示例
fn main() {
let mut bytes = [0u8; 8];
bytes[..4].copy_from_slice(&[1, 2, 3, 4]);
// 把前 4 个字节搬到偏移 2 处:源与目标重叠,copy_within 自己处理
bytes.copy_within(0..4, 2);
println!("after overlap copy: {bytes:?}");
let mut label = *b"abcdefgh";
// 把尾部三个字符搬到开头,剩余保持原位
label.copy_within(5..8, 0);
println!("moved tail: {:?}", std::str::from_utf8(&label).unwrap());
// 目标区间越界会 panic,先按长度自查
let n = 3;
if n * 2 <= label.len() {
label.copy_within(0..n, n);
println!("shifted: {:?}", std::str::from_utf8(&label).unwrap());
}
}