我想采取一个可变片,并将内容复制到两个新的可变片。每片是原来的一半。如何从一个切片创建两个新的可变片?
我尝试#1:
let my_list: &mut [u8] = &mut [0, 1, 2, 3, 4, 5];
let list_a: &mut [u8] = my_list[0..3].clone();
let list_b: &mut [u8] = my_list[3..6].clone();
println!("{:?}", my_list);
println!("{:?}", list_a);
println!("{:?}", list_b);
输出:
error: no method named `clone` found for type `[u8]` in the current scope
--> src/main.rs:3:43
|
3 | let list_a: &mut [u8] = my_list[0..3].clone();
| ^^^^^
error: no method named `clone` found for type `[u8]` in the current scope
--> src/main.rs:4:43
|
4 | let list_b: &mut [u8] = my_list[3..6].clone();
| ^^^^^
我尝试#2:
let my_list: &mut [u8] = &mut [0, 1, 2, 3, 4, 5];
let list_a: &mut [u8] = my_list[0..3].to_owned();
let list_b: &mut [u8] = my_list[3..6].to_owned();
println!("{:?}", my_list);
println!("{:?}", list_a);
println!("{:?}", list_b);
输出:
error[E0308]: mismatched types
--> src/main.rs:12:29
|
12 | let list_a: &mut [u8] = my_list[0..3].to_owned();
| ^^^^^^^^^^^^^^^^^^^^^^^^ expected &mut [u8], found struct `std::vec::Vec`
|
= note: expected type `&mut [u8]`
found type `std::vec::Vec<u8>`
= help: try with `&mut my_list[0..3].to_owned()`
error[E0308]: mismatched types
--> src/main.rs:13:29
|
13 | let list_b: &mut [u8] = my_list[3..6].to_owned();
| ^^^^^^^^^^^^^^^^^^^^^^^^ expected &mut [u8], found struct `std::vec::Vec`
|
= note: expected type `&mut [u8]`
found type `std::vec::Vec<u8>`
= help: try with `&mut my_list[3..6].to_owned()`
我可以用两个Vec<u8>
,只是在输入回路和推克隆价值我想,但我希望能有一个更好的方式来做到这一点:
extern crate rand;
use rand::{thread_rng, Rng};
fn main() {
let my_list: &mut [u8] = &mut [0; 100];
thread_rng().fill_bytes(my_list);
let list_a = &mut Vec::new();
let list_b = &mut Vec::new();
for i in 0..my_list.len() {
if i < my_list.len()/2 {
list_a.push(my_list[i].clone());
} else {
list_b.push(my_list[i].clone());
}
}
println!("{:?}", list_a.as_slice());
println!("{:?}", list_b.as_slice());
println!("{:?}", my_list);
}
不错,我没有意识到这个功能的存在。 –
不错,绝对是我目前看到的最干净的。使用Vec vs&[]或者&mut []有什么不利之处?很明显,Vec很容易处理,但似乎可能会有一些开销。 – user439299
切片只是一种表示形式,如果调用as_slice(),它将借用对矢量的引用,但不会创建新的。如果有疑问,请检查生命周期参数(http://doc.rust-lang.org/std/vec/struct.Vec.html#method.as_slice),它具有与向量相同的生命周期。 – snf