Appendix B — Quick Reference Tables
local graph
Appendix B — Quick Reference Tables
Section titled “Appendix B — Quick Reference Tables”This appendix provides condensed reference material for common decisions during Rust development. These tables and diagrams serve as quick lookups rather than comprehensive explanations. Each topic receives thorough coverage in earlier chapters; this appendix distills that knowledge into scannable formats for daily use.
Smart pointer selection guide
Choosing the right smart pointer depends on ownership semantics, mutability requirements, and whether the code is single-threaded or concurrent. The following table summarizes the primary smart pointers and their use cases:
| Type | Ownership | Mutability | Thread-safe | Use case |
|---|---|---|---|---|
Box<T> | Single | Through owner | Send if T: Send | Heap allocation, recursive types |
Rc<T> | Shared | Immutable | No | Single-threaded shared ownership |
Arc<T> | Shared | Immutable | Yes | Multi-threaded shared ownership |
RefCell<T> | Single | Interior mutability | No | Runtime borrow checking |
Mutex<T> | Single | Interior mutability | Yes | Shared mutable state across threads |
RwLock<T> | Single | Interior mutability | Yes | Many readers, occasional writers |
| Type | Ownership | Mutability | Thread-safe | Use case |
|---|---|---|---|---|
Cell<T> | Single | Interior mutability | No | Copy types, no borrow needed |
Common combinations extend these base capabilities:
| Combination | Use |
|---|---|
Rc<RefCell<T>> | Shared ownership with mutation (single-threaded) |
Arc<Mutex<T>> | Shared ownership with mutation (multi-threaded) |
Arc<RwLock<T>> | Shared ownership, read-heavy workloads |
Box<dyn Trait> | Owned trait objects on the heap |
Rc<dyn Trait> | Shared trait objects (single-threaded) |
Arc<dyn Trait> | Shared trait objects (multi-threaded) |
The decision flow for selecting a smart pointer follows this pattern:
graph TD
H{"Need heap allocation?"} -- Yes --> SO{"Shared ownership?"}
H -- No --> ST["Use stack allocation"]
SO -- No --> BX["Box#lt;T#gt;"]
SO -- Yes --> MT{"Multi-threaded?"}
MT -- No --> NM1{"Need mutation?"}
MT -- Yes --> NM2{"Need mutation?"}
NM1 -- No --> RC["Rc#lt;T#gt;"]
NM1 -- Yes --> RCR["Rc#lt;RefCell#lt;T#gt;#gt;"]
NM2 -- No --> AR["Arc#lt;T#gt;"]
NM2 -- Yes --> RH{"Read-heavy?"}
RH -- No --> AM["Arc#lt;Mutex#lt;T#gt;#gt;"]
RH -- Yes --> ARW["Arc#lt;RwLock#lt;T#gt;#gt;"]
[!visual-conversion] Smart pointer selection decision tree. Print flowchart (PDF 654, printed p. 646) recreated in Mermaid; every node label and Yes/No edge verbatim. (The OCR had looped on this figure ~110 times and lost the section heading and paragraph below, restored from the scan.)
Error handling decision tree
Error handling strategy depends on whether recovery is possible, whether errors should propagate, and the context (library vs application).
This decision tree guides the choice:
graph TD
O{"Can the error occur?"} -- No --> NH["No handling needed"]
O -- Yes --> CR{"Can caller recover?"}
CR -- No --> BG{"Is it a bug?"}
CR -- Yes --> RR["Return Result#lt;T, E#gt;"] --> SH{"Should caller handle inline?"}
BG -- Yes --> PA["panic! or assert!"]
BG -- No --> LB{"Is this a library?"}
LB -- Yes --> RL["Return Result, let caller decide"]
LB -- No --> LE["Log and exit gracefully"]
SH -- Yes --> MI["match or if let"]
SH -- No --> PQ["Propagate with ?"]
[!visual-conversion] Error handling strategy decision tree. Print flowchart (PDF 655, printed p. 647) recreated in Mermaid; every node label and Yes/No edge verbatim.
The following table maps common scenarios to their recommended handling approach:
| Scenario | Approach | Example |
|---|---|---|
| Index out of bounds (bug) | panic! via [] operator | vec[invalid_index] |
| Index out of bounds (input) | Option via .get() | vec.get(user_index) |
| File not found | Result with ? propagation | File::open(path)? |
| Parse error from user input | Result with match | input.parse::<i32>() |
| Scenario | Approach | Example |
|---|---|---|
| Configuration missing | Result or Option with default | .unwrap_or_default() |
| Impossible state reached | unreachable!() | Match arm that cannot occur |
| Unimplemented feature | todo!() or unimplemented!() | Placeholder during development |
| Assertion in tests | assert!, assert_eq! | Test validation |
Error type selection
| Situation | Error type | Notes |
|---|---|---|
| Single failure mode | Custom unit struct | struct NotFound; |
| Multiple failure modes | Custom enum | Variants for each case |
| IO operations | std::io::Error | Standard, widely understood |
| Quick prototyping | Box<dyn Error> | Accepts any error type |
| Application code | anyhow::Error | Convenient, good backtraces |
| Library code | thiserror derive | Structured, composable |
Conversion trait cheat sheet
Rust’s conversion traits form a hierarchy that enables flexible APIs. Understanding when to implement or use each trait prevents unnecessary allocations and enables generic code.
Core conversion traits
| Trait | Method | Direction | Cost | Use |
|---|---|---|---|---|
From<T> | from(T) -> Self | T → Self | Varies | Type conversions, constructors |
Into<T> | into(self) -> T | Self → T | Varies | Auto-derived from From |
TryFrom<T> | try_from(T) -> Result<Self, E> | T → Self | Varies | Fallible conversions |
TryInto<T> | try_into(self) -> Result<T, E> | Self → T | Varies | Auto-derived from TryFrom |
AsRef<T> | as_ref(&self) -> &T | &Self → &T | Free | Borrowing as another type |
AsMut<T> | as_mut(&mut self) -> &mut T | &mut Self → &mut T | Free | Mutable borrowing |
Borrow<T> | borrow(&self) -> &T | &Self → &T | Free | Hash/Eq consistent borrowing |
ToOwned | to_owned(&self) -> Owned | &Self → Owned | Clones | Borrowed to owned |
Deref | deref(&self) -> &Target | &Self → &Target | Free | Smart pointer transparency |
Relationship between traits
The conversion traits relate to each other in specific ways:
graph LR
subgraph BR["Borrowing"]
DR["Deref#lt;Target=T#gt;"] -- enables --> AR["AsRef#lt;T#gt;"] -- "similar but" --> BO["Borrow#lt;T#gt;"]
end
subgraph IN["Infallible"]
FR["From#lt;T#gt;"] -- auto-implements --> IT["Into#lt;T#gt;"]
end
subgraph FA["Fallible"]
TF["TryFrom#lt;T#gt;"] -- auto-implements --> TI["TryInto#lt;T#gt;"]
end
FR -- "if infallible" --> TF
[!visual-conversion] Conversion trait relationships. Print diagram (PDF 658, printed p. 650) recreated in Mermaid; three frames, all nodes and edge labels verbatim.
When to use each trait
| Goal | Implement | Accept as parameter |
|---|---|---|
| Convert owned value to new type | From<T> | Into<T> |
| Convert with possible failure | TryFrom<T> | TryInto<T> |
| Accept borrowed or owned strings | - | AsRef<str> or impl Into<String> |
| Accept path-like arguments | - | AsRef<Path> |
| HashMap key lookup without allocation | Borrow<T> | - |
| Enable * operator | Deref | - |
| Clone from reference | ToOwned | - |
Common conversions reference
| From | To | Methods |
|---|---|---|
&str | String | .to_string(), .to_owned(), String::from() |
String | &str | &s, .as_str() |
&[T] | Vec<T> | .to_vec(), .to_owned() |
Vec<T> | &[T] | &v, .as_slice() |
&Path | PathBuf | .to_path_buf(), .to_owned() |
PathBuf | &Path | &p, .as_path() |
i32 | i64 | .into(), i64::from() |
i64 | i32 | .try_into() (fallible) |
&str | i32 | .parse() (fallible) |
i32 | String | .to_string() |
OOP to Rust translation table
This table maps common OOP patterns and constructs to their Rust equivalents. The Rust approach often differs structurally while achieving the same goals.
Class and object concepts
| OOP | Rust | Notes |
|---|---|---|
| Class | struct + impl | Data and methods separated |
| Constructor | new() convention or Default | No special syntax |
| Destructor | Drop trait | Called automatically when value goes out of scope |
| OOP | Rust | Notes |
|---|---|---|
| Instance field | struct field | struct Point { x: i32, y: i32 } |
| Instance method | impl with &self or &mut self | fn area(&self) -> f64 |
| Static method | impl without self | fn new() -> Self |
| Static field | const or static | const MAX: i32 = 100; |
| this / self keyword | self, &self, &mut self | Explicit receiver parameter |
| Getter | Method returning field reference | fn name(&self) -> &str |
| Setter | Method taking &mut self | fn set_name(&mut self, name: String) |
Inheritance and polymorphism
| OOP | Rust | Notes |
|---|---|---|
| Interface | trait | trait Drawable { fn draw(&self); } |
| Abstract class | trait with default methods | Cannot have fields |
| Inheritance | Composition + traits | No struct inheritance |
| extends (class) | Embed struct + Deref | struct Manager { employee: Employee } |
| implements (interface) | impl Trait for Type | impl Drawable for Circle |
| Method overriding | Trait implementation | Each type provides its own |
| OOP | Rust | Notes |
|---|---|---|
| super call | Explicit delegation | self.inner.method() |
| Virtual method | Trait object method | &dyn Trait for dynamic dispatch |
| Non-virtual method | Generic with trait bound | fn draw<T: Drawable>(item: &T) |
| Multiple inheritance | Multiple trait bounds | T: Read + Write + Seek |
| Abstract method | Trait method without default | Must be implemented |
Access control
| OOP | Rust | Notes |
|---|---|---|
| public | pub | Visible everywhere |
| private | (default) | Visible in current module only |
| protected | pub(crate) or pub(super) | No exact equivalent |
| internal (C#) | pub(crate) | Visible within crate |
| Package-private (Java) | pub(super) | Visible to parent module |
| Friend class (C++) | pub(in path) | Fine-grained visibility |
Common patterns translation
| Pattern | Rust approach |
|---|---|
| Singleton | static with OnceLock or lazy_static |
| Pattern | Rust approach |
|---|---|
| Factory | Associated function returning Self or Box<dyn Trait> |
| Builder | Struct with chainable methods returning Self |
| Strategy | Trait object (Box<dyn Strategy>) or enum |
| Observer | Channels (mpsc) or callback closures |
| Decorator | Wrapper struct implementing same trait |
| Adapter | Newtype pattern with trait implementation |
| Template Method | Trait with default methods calling required methods |
| Null Object | Option<T> or dedicated unit struct |
| RAII | Default behavior (Drop trait) |
Type system mappings
| OOP | Rust | Example |
|---|---|---|
| Generic class | Generic struct | struct Container<T> { item: T } |
| Generic method | Generic function | fn process<T: Clone>(item: T) |
| Bounded generic | Trait bounds | <T: Display + Debug> |
| Wildcard (?) | impl Trait or dyn Trait | fn print(item: &dyn Display) |
| Covariance | Phantom types, limited | Complex topic |
| OOP | Rust | Example |
|---|---|---|
| Enum (Java/C#) | enum (much more powerful) | Variants can hold data |
| Nullable type | Option<T> | Option<String> |
| Exception | Result<T, E> | Result<Data, Error> |
| Try-catch | match or ? operator | file.read()?.parse()? |
| Checked exception | Result in signature | Part of function type |
Quick syntax reference
| Java / C# | Rust |
|---|---|
class Foo {} | struct Foo {} + impl Foo {} |
interface Bar {} | trait Bar {} |
class Foo implements Bar | impl Bar for Foo |
Foo foo = new Foo() | let foo = Foo::new() |
foo.method() | foo.method() |
Foo.staticMethod() | Foo::static_method() |
foo instanceof Bar | Pattern matching or Any trait |
(Bar) foo | .into(), as, or pattern match |
foo == bar (reference) | std::ptr::eq(&foo, &bar) |
foo.equals(bar) (value) | foo == bar (with PartialEq) |
foo.hashCode() | Implement Hash trait |
foo.toString() | Implement Display or Debug trait |
foo.clone() | foo.clone() (with Clone trait) |