Containers, wrappers, and cells all provide ways to access the data they enclose. Accessor methods often have variants to access the data by value, by reference, and by mutable reference.
In general, the get
`getfamily of methods is used to access contained data without any risk of thread failure; they return
` family of methods is used to access contained
data without any risk of thread failure; they return Option
`Optionas appropriate. This name is chosen rather than names like
` as
appropriate. This name is chosen rather than names like find
`findor
` or
lookup
`lookup` because it is appropriate for a wider range of container types.
For a container with keys/indexes of type K
`Kand elements of type
` and elements of type V
`V`:
// Look up element without failing fn get(&self, key: K) -> Option<&V> fn get_mut(&mut self, key: K) -> Option<&mut V> // Convenience for .get(key).map(|elt| elt.clone()) fn get_clone(&self, key: K) -> Option<V> // Lookup element, failing if it is not found: impl Index<K, V> for Container { ... } impl IndexMut<K, V> for Container { ... }
Prefer specific conversion functions like as_bytes
`as_bytesor
` or into_vec
`into_vec` whenever
possible. Otherwise, use:
// Extract contents without failing fn get(&self) -> &V fn get_mut(&mut self) -> &mut V fn unwrap(self) -> V
Copy
`Copy` data// Extract contents without failing fn get(&self) -> V
Option
`Option`-like typesFinally, we have the cases of types like Option
`Optionand
` and Result
`Result`, which
play a special role for failure.
For Option<V>
`Option
// Extract contents or fail if not available fn assert(self) -> V fn expect(self, &str) -> V
For Result<V, E>
`Result
// Extract the contents of Ok variant; fail if Err fn assert(self) -> V // Extract the contents of Err variant; fail if Ok fn assert_err(self) -> E