在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 …Run Code Online (Sandbox Code Playgroud) 我有一个需要在单个阵列的两个部分上运行的功能.目的是能够构建一个#[nostd]分配器,该分配器可以将更大数组的变量片返回给调用者,并挂起到数组的其余部分以供将来分配.
这是失败的示例代码:
fn split<'a>(mut item: &'a mut [i32], place: usize) -> (&'a mut [i32], &'a mut [i32]) {
(&mut item[0..place], &mut item[place..])
}
fn main() {
let mut mem: [i32; 2048] = [1; 2048];
let (mut array0, mut array1) = split(&mut mem[..], 768);
array0[0] = 4;
println!("{:?} {:?}", array0[0], array1[0]);
}
Run Code Online (Sandbox Code Playgroud)
错误如下:
error[E0499]: cannot borrow `*item` as mutable more than once at a time
--> src/main.rs:2:32
|
2 | (&mut item[0..place], &mut item[place..])
| ---- ^^^^ second mutable …Run Code Online (Sandbox Code Playgroud) 我在结构中有一个固定大小的缓冲区Bytes,我想在其中复制一些数据。
目前我唯一能看到的就是从开头切下一部分,添加我想要的内容,然后在末尾添加切片,但我确信这会产生一两个我想要的大副本避免,我只需要更新缓冲区的中间。有没有一种简单的方法可以在不使用的情况下做到这一点unsafe?
有多个std::collections::LinkedLists 的正确方法是什么,这些列表的编号在编译时是未知的?
我正在填充数据以及合并它们(例如使用append()).我认为有一个包含这些列表的向量或包含对这些列表的引用会很好.
我尝试过以下方法:
use std::collections::LinkedList;
fn listtest() {
let mut v: Vec<LinkedList<i32>> = Vec::new();
v.push(LinkedList::new()); // first list
v.push(LinkedList::new()); // second list
v[0].push_back(1); // fill with data
v[1].push_back(3); // fill with data
v[0].append(&mut v[1]); // merge lists
}
fn main() {
listtest();
}
Run Code Online (Sandbox Code Playgroud)
这无法编译,因为我v在使用时有两个可变引用append().我也尝试过使用Vec<&mut LinkedList<i32>>,但没有成功.
这个问题的正确方法是什么?