首页 > 解决方案 > How can I split a vector into smaller vectors of size N?

问题描述

How to split a vector

let v: Vec<u8>; // vector with size x

into a vector of vectors of maxsize n? Pseudocode:

let n: usize = 1024;
let chunks_list: Vec<Vec<u8>> = chunks(v, n);

or using slices (to avoid copying):

let v: &[u8]; 
let chunks_list: Vec<&[u8]> = chunks(v, n);

标签: vectorrust

解决方案


Rust slices already contain the necessary method for that: chunks.

Starting from this:

let src: Vec<u8> = vec![1, 2, 3, 4, 5];

you can get a vector of slices (no copy):

let dst: Vec<&[u8]> = src.chunks(3).collect();

or a vector of vectors (slower, heavier):

let dst: Vec<Vec<u8>> = src.chunks(3).map(|s| s.into()).collect();

playground


推荐阅读