在Go中,复制切片是标准费用,如下所示:
# It will figure out the details to match slice sizes
dst = copy(dst[n:], src[:m])
Run Code Online (Sandbox Code Playgroud)
在Rust中,我找不到与替换类似的方法.我想出的东西看起来像这样:
fn copy_slice(dst: &mut [u8], src: &[u8]) -> usize {
let mut c = 0;
for (&mut d, &s) in dst.iter_mut().zip(src.iter()) {
d = s;
c += 1;
}
c
}
Run Code Online (Sandbox Code Playgroud)
不幸的是,我得到了这个我无法解决的编译错误:
error[E0384]: re-assignment of immutable variable `d`
--> src/main.rs:4:9
|
3 | for (&mut d, &s) in dst.iter_mut().zip(src.iter()) {
| - first assignment to `d`
4 | d = s;
| ^^^^^ re-assignment of immutable variable
Run Code Online (Sandbox Code Playgroud)
我怎么设置d?有没有更好的方法来复制切片?
blu*_*uss 35
是的,使用该方法clone_from_slice(),它对任何实现的元素类型都是通用的Clone.
fn main() {
let mut x = vec![0; 8];
let y = [1, 2, 3];
x[..3].clone_from_slice(&y);
println!("{:?}", x);
// Output:
// [1, 2, 3, 0, 0, 0, 0, 0]
}
Run Code Online (Sandbox Code Playgroud)
目的地x是一个&mut [T]切片,或任何与之相关的东西,就像一个可变的Vec<T>向量.您需要切割目标和源,以便它们的长度匹配.
从Rust 1.9开始,您也可以使用copy_from_slice().这工作方式相同,但使用Copy特征代替Clone,并且是直接包装memcpy.编译器可以优化clone_from_slice等同于copy_from_slice在适用时,但它仍然是有用的.
这段代码有效,尽管我不确定它是否是最好的方法。
fn copy_slice(dst: &mut [u8], src: &[u8]) -> usize {
let mut c = 0;
for (d, s) in dst.iter_mut().zip(src.iter()) {
*d = *s;
c += 1;
}
c
}
Run Code Online (Sandbox Code Playgroud)
显然没有明确指定访问权限就可以了。然而,我仍然对此感到困惑,我的心智模型还没有涵盖那里真正发生的事情。当涉及到这些事情时,我的解决方案大多是反复试验,而我宁愿真正理解。
| 归档时间: |
|
| 查看次数: |
20770 次 |
| 最近记录: |