Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get subslices?

Tags:

rust

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.

like image 706
user19018 Avatar asked May 16 '15 06:05

user19018


1 Answers

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.

like image 67
Vladimir Matveev Avatar answered Oct 02 '22 23:10

Vladimir Matveev