]> git.proxmox.com Git - rustc.git/blob - src/doc/nomicon/vec-deref.md
Imported Upstream version 1.3.0+dfsg1
[rustc.git] / src / doc / nomicon / vec-deref.md
1 % Deref
2
3 Alright! We've got a decent minimal stack implemented. We can push, we can
4 pop, and we can clean up after ourselves. However there's a whole mess of
5 functionality we'd reasonably want. In particular, we have a proper array, but
6 none of the slice functionality. That's actually pretty easy to solve: we can
7 implement `Deref<Target=[T]>`. This will magically make our Vec coerce to, and
8 behave like, a slice in all sorts of conditions.
9
10 All we need is `slice::from_raw_parts`. It will correctly handle empty slices
11 for us. Later once we set up zero-sized type support it will also Just Work
12 for those too.
13
14 ```rust,ignore
15 use std::ops::Deref;
16
17 impl<T> Deref for Vec<T> {
18 type Target = [T];
19 fn deref(&self) -> &[T] {
20 unsafe {
21 ::std::slice::from_raw_parts(*self.ptr, self.len)
22 }
23 }
24 }
25 ```
26
27 And let's do DerefMut too:
28
29 ```rust,ignore
30 use std::ops::DerefMut;
31
32 impl<T> DerefMut for Vec<T> {
33 fn deref_mut(&mut self) -> &mut [T] {
34 unsafe {
35 ::std::slice::from_raw_parts_mut(*self.ptr, self.len)
36 }
37 }
38 }
39 ```
40
41 Now we have `len`, `first`, `last`, indexing, slicing, sorting, `iter`,
42 `iter_mut`, and all other sorts of bells and whistles provided by slice. Sweet!