How to get subslices?

2019-02-21 17:16发布

问题:

I have a variable a of type &[T]; how can I get a reference to a subslice of a?

As a concrete example, I'd like to get the first and second halves of a, provided a.len() is even.

回答1:

You use slicing syntax for that:

fn main() {
    let data: &[u8] = b"12345678";
    println!("{:?} - {:?}", &data[..data.len()/2], &data[data.len()/2..]);
}

(try it here)

The general syntax is

&slice[start_idx..end_idx]

which gives a slice derived from slice, starting at start_idx and ending at end_idx-1 (that is, item at the right index is not included). Either index could be omitted (even both), which would mean zero or slice length, correspondingly.

Note that if you want to split a slice at some position into two slices, it is often better to use split_at() method:

let data = b"12345678";
let (left, right): (&[u8], &[u8]) = data.split_at(4);

Moreover, this is the only way to obtain two mutable slices out of another mutable slice:

let mut data: Vec<u8> = vec![1, 2, 3, 4, 5, 6, 7, 8];
let data_slice: &mut [u8] = &mut data[..];
let (left, right): (&mut [u8], &mut [u8]) = data_slice.split_at_mut(4);

However, these basic things are explained in the official book on Rust. You should start from there if you want to learn Rust.



标签: rust