Ben Chuanlong Du's Blog

It is never too late to learn.

Slice in Rust

Things on this page are fragmentary and immature notes/thoughts of the author. Please read with your own judgement!

In [ ]:
:timing
:sccache 1

Tips and Traps

  1. A slice is a dynamically-sized view into a contiguous sequence. It is basically a fat pointer which consists of a pointer and a length. For this reason, a slice has a len method. As a matter of fact, many methods of array and Vec are implemented via slice.
In [6]:
let v = vec![0, 1, 2, 3, 4, 5, 6, 7, 8, 9];
In [13]:
&v[2..7]
Out[13]:
[2, 3, 4, 5, 6]
In [14]:
&v[2..]
Out[14]:
[2, 3, 4, 5, 6, 7, 8, 9]
In [16]:
&v[..4]
Out[16]:
[0, 1, 2, 3]

Nested Slices

Slices in Rust can be nested. That is, you can get (sub) slice out of a slice.

In [21]:
&v[2..7][1..3]
Out[21]:
[3, 4]
In [9]:
&v[2..7].binary_search(&8)
Out[9]:
Err(5)
In [10]:
&v[2..7].binary_search(&4)
Out[10]:
Ok(2)
In [ ]:

Comments