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.
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.
You use slicing syntax for that:
(try it here)
The general syntax is
which gives a slice derived from
slice
, starting atstart_idx
and ending atend_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:Moreover, this is the only way to obtain two mutable slices out of another mutable slice:
However, these basic things are explained in the official book on Rust. You should start from there if you want to learn Rust.