]> git.proxmox.com Git - rustc.git/blame - src/doc/style/style/naming/containers.md
New upstream version 1.12.1+dfsg1
[rustc.git] / src / doc / style / style / naming / containers.md
CommitLineData
85aaf69f
SL
1% Common container/wrapper methods [FIXME: needs RFC]
2
3Containers, wrappers, and cells all provide ways to access the data
4they enclose. Accessor methods often have variants to access the data
5by value, by reference, and by mutable reference.
6
7In general, the `get` family of methods is used to access contained
bd371182 8data without any risk of thread failure; they return `Option` as
85aaf69f
SL
9appropriate. 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
14For 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
18fn get(&self, key: K) -> Option<&V>
19fn get_mut(&mut self, key: K) -> Option<&mut V>
20
21// Convenience for .get(key).map(|elt| elt.clone())
22fn get_clone(&self, key: K) -> Option<V>
23
24// Lookup element, failing if it is not found:
25impl Index<K, V> for Container { ... }
26impl IndexMut<K, V> for Container { ... }
27```
28
29#### Wrappers/Cells
30
31Prefer specific conversion functions like `as_bytes` or `into_vec` whenever
32possible. Otherwise, use:
33
a7813a04 34```rust,ignore
85aaf69f
SL
35// Extract contents without failing
36fn get(&self) -> &V
37fn get_mut(&mut self) -> &mut V
38fn unwrap(self) -> V
39```
40
41#### Wrappers/Cells around `Copy` data
42
a7813a04 43```rust,ignore
85aaf69f
SL
44// Extract contents without failing
45fn get(&self) -> V
46```
47
48#### `Option`-like types
49
50Finally, we have the cases of types like `Option` and `Result`, which
51play a special role for failure.
52
53For `Option<V>`:
54
a7813a04 55```rust,ignore
85aaf69f
SL
56// Extract contents or fail if not available
57fn assert(self) -> V
58fn expect(self, &str) -> V
59```
60
61For `Result<V, E>`:
62
a7813a04 63```rust,ignore
85aaf69f
SL
64// Extract the contents of Ok variant; fail if Err
65fn assert(self) -> V
66
67// Extract the contents of Err variant; fail if Ok
68fn assert_err(self) -> E
69```