]>
Commit | Line | Data |
---|---|---|
85aaf69f SL |
1 | % Common container/wrapper methods [FIXME: needs RFC] |
2 | ||
3 | Containers, wrappers, and cells all provide ways to access the data | |
4 | they enclose. Accessor methods often have variants to access the data | |
5 | by value, by reference, and by mutable reference. | |
6 | ||
7 | In general, the `get` family of methods is used to access contained | |
bd371182 | 8 | data without any risk of thread failure; they return `Option` as |
85aaf69f SL |
9 | appropriate. This name is chosen rather than names like `find` or |
10 | `lookup` because it is appropriate for a wider range of container types. | |
11 | ||
12 | #### Containers | |
13 | ||
14 | For a container with keys/indexes of type `K` and elements of type `V`: | |
15 | ||
a7813a04 | 16 | ```rust,ignore |
85aaf69f SL |
17 | // Look up element without failing |
18 | fn get(&self, key: K) -> Option<&V> | |
19 | fn get_mut(&mut self, key: K) -> Option<&mut V> | |
20 | ||
21 | // Convenience for .get(key).map(|elt| elt.clone()) | |
22 | fn get_clone(&self, key: K) -> Option<V> | |
23 | ||
24 | // Lookup element, failing if it is not found: | |
25 | impl Index<K, V> for Container { ... } | |
26 | impl IndexMut<K, V> for Container { ... } | |
27 | ``` | |
28 | ||
29 | #### Wrappers/Cells | |
30 | ||
31 | Prefer specific conversion functions like `as_bytes` or `into_vec` whenever | |
32 | possible. Otherwise, use: | |
33 | ||
a7813a04 | 34 | ```rust,ignore |
85aaf69f SL |
35 | // Extract contents without failing |
36 | fn get(&self) -> &V | |
37 | fn get_mut(&mut self) -> &mut V | |
38 | fn unwrap(self) -> V | |
39 | ``` | |
40 | ||
41 | #### Wrappers/Cells around `Copy` data | |
42 | ||
a7813a04 | 43 | ```rust,ignore |
85aaf69f SL |
44 | // Extract contents without failing |
45 | fn get(&self) -> V | |
46 | ``` | |
47 | ||
48 | #### `Option`-like types | |
49 | ||
50 | Finally, we have the cases of types like `Option` and `Result`, which | |
51 | play a special role for failure. | |
52 | ||
53 | For `Option<V>`: | |
54 | ||
a7813a04 | 55 | ```rust,ignore |
85aaf69f SL |
56 | // Extract contents or fail if not available |
57 | fn assert(self) -> V | |
58 | fn expect(self, &str) -> V | |
59 | ``` | |
60 | ||
61 | For `Result<V, E>`: | |
62 | ||
a7813a04 | 63 | ```rust,ignore |
85aaf69f SL |
64 | // Extract the contents of Ok variant; fail if Err |
65 | fn assert(self) -> V | |
66 | ||
67 | // Extract the contents of Err variant; fail if Ok | |
68 | fn assert_err(self) -> E | |
69 | ``` |