]> git.proxmox.com Git - rustc.git/blob - src/doc/nomicon/src/vec/vec-deref.md
New upstream version 1.55.0+dfsg1
[rustc.git] / src / doc / nomicon / src / vec / 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 <!-- ignore: simplified code -->
15 ```rust,ignore
16 use std::ops::Deref;
17
18 impl<T> Deref for Vec<T> {
19 type Target = [T];
20 fn deref(&self) -> &[T] {
21 unsafe {
22 std::slice::from_raw_parts(self.ptr.as_ptr(), self.len)
23 }
24 }
25 }
26 ```
27
28 And let's do DerefMut too:
29
30 <!-- ignore: simplified code -->
31 ```rust,ignore
32 use std::ops::DerefMut;
33
34 impl<T> DerefMut for Vec<T> {
35 fn deref_mut(&mut self) -> &mut [T] {
36 unsafe {
37 std::slice::from_raw_parts_mut(self.ptr.as_ptr(), self.len)
38 }
39 }
40 }
41 ```
42
43 Now we have `len`, `first`, `last`, indexing, slicing, sorting, `iter`,
44 `iter_mut`, and all other sorts of bells and whistles provided by slice. Sweet!