slice - 如何从一个切片创建两个新的可变切片?

标签 slice rust

我想获取一个可变切片并将内容复制到两个新的可变切片中。每一片都是原片的一半。

我的尝试 #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);
}

最佳答案

split_atsplit_at_mut方法将为您提供两个切片,然后您可以复制它们,如果借用检查器允许,您甚至可以安全地使用它们而无需复制。

let (list_a, list_b) = my_list.split_at_mut(my_list.len()/2)

关于slice - 如何从一个切片创建两个新的可变切片?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24872634/

相关文章:

arrays - 如何将 C 样式数组修改为 D 样式数组?

python - 使用两个 bool 数组索引 2D np.array 时出现意外行为

arrays - 解析显式数组

rust - 引用字段调用回调

multithreading - 如何为 RustBox 实现 Sync?

generics - 如何从盒装特征对象获取对结构的引用?

json - 解码嵌套 json 会导致空值

Golang slice 附加和重新分配

macros - 编译时如何在宏之间进行选择?

string - 在 Rust 中将 ascii 字符串文字转换为 &[u8]?