Skip to content
ImagineWorld

Appendix B — Quick Reference Tables

node_idnode-book_oop-to-rust_back-appendix-b-quick-reference-tables
node_typebook-part
schema_profileworld.chapter_node.v1
statusactive
entropyhigh
manifoldworld
domainimagineworld.net
authorityinforms
layercorpus
chapter_titleAppendix B — Quick Reference Tables
governed_byCORPUS
constitutional_citationCONSTITUTION
local graph

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:

TypeOwnershipMutabilityThread-safeUse case
Box<T>SingleThrough ownerSend if T: SendHeap allocation, recursive types
Rc<T>SharedImmutableNoSingle-threaded shared ownership
Arc<T>SharedImmutableYesMulti-threaded shared ownership
RefCell<T>SingleInterior mutabilityNoRuntime borrow checking
Mutex<T>SingleInterior mutabilityYesShared mutable state across threads
RwLock<T>SingleInterior mutabilityYesMany readers, occasional writers
TypeOwnershipMutabilityThread-safeUse case
Cell<T>SingleInterior mutabilityNoCopy types, no borrow needed

Common combinations extend these base capabilities:

CombinationUse
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:

ScenarioApproachExample
Index out of bounds (bug)panic! via [] operatorvec[invalid_index]
Index out of bounds (input)Option via .get()vec.get(user_index)
File not foundResult with ? propagationFile::open(path)?
Parse error from user inputResult with matchinput.parse::<i32>()
ScenarioApproachExample
Configuration missingResult or Option with default.unwrap_or_default()
Impossible state reachedunreachable!()Match arm that cannot occur
Unimplemented featuretodo!() or unimplemented!()Placeholder during development
Assertion in testsassert!, assert_eq!Test validation

Error type selection

SituationError typeNotes
Single failure modeCustom unit structstruct NotFound;
Multiple failure modesCustom enumVariants for each case
IO operationsstd::io::ErrorStandard, widely understood
Quick prototypingBox<dyn Error>Accepts any error type
Application codeanyhow::ErrorConvenient, good backtraces
Library codethiserror deriveStructured, 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

TraitMethodDirectionCostUse
From<T>from(T) -> SelfT → SelfVariesType conversions, constructors
Into<T>into(self) -> TSelf → TVariesAuto-derived from From
TryFrom<T>try_from(T) -> Result<Self, E>T → SelfVariesFallible conversions
TryInto<T>try_into(self) -> Result<T, E>Self → TVariesAuto-derived from TryFrom
AsRef<T>as_ref(&self) -> &T&Self → &TFreeBorrowing as another type
AsMut<T>as_mut(&mut self) -> &mut T&mut Self → &mut TFreeMutable borrowing
Borrow<T>borrow(&self) -> &T&Self → &TFreeHash/Eq consistent borrowing
ToOwnedto_owned(&self) -> Owned&Self → OwnedClonesBorrowed to owned
Derefderef(&self) -> &Target&Self → &TargetFreeSmart 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

GoalImplementAccept as parameter
Convert owned value to new typeFrom<T>Into<T>
Convert with possible failureTryFrom<T>TryInto<T>
Accept borrowed or owned strings-AsRef<str> or impl Into<String>
Accept path-like arguments-AsRef<Path>
HashMap key lookup without allocationBorrow<T>-
Enable * operatorDeref-
Clone from referenceToOwned-

Common conversions reference

FromToMethods
&strString.to_string(), .to_owned(), String::from()
String&str&s, .as_str()
&[T]Vec<T>.to_vec(), .to_owned()
Vec<T>&[T]&v, .as_slice()
&PathPathBuf.to_path_buf(), .to_owned()
PathBuf&Path&p, .as_path()
i32i64.into(), i64::from()
i64i32.try_into() (fallible)
&stri32.parse() (fallible)
i32String.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

OOPRustNotes
Classstruct + implData and methods separated
Constructornew() convention or DefaultNo special syntax
DestructorDrop traitCalled automatically when value goes out of scope
OOPRustNotes
Instance fieldstruct fieldstruct Point { x: i32, y: i32 }
Instance methodimpl with &self or &mut selffn area(&self) -> f64
Static methodimpl without selffn new() -> Self
Static fieldconst or staticconst MAX: i32 = 100;
this / self keywordself, &self, &mut selfExplicit receiver parameter
GetterMethod returning field referencefn name(&self) -> &str
SetterMethod taking &mut selffn set_name(&mut self, name: String)

Inheritance and polymorphism

OOPRustNotes
Interfacetraittrait Drawable { fn draw(&self); }
Abstract classtrait with default methodsCannot have fields
InheritanceComposition + traitsNo struct inheritance
extends (class)Embed struct + Derefstruct Manager { employee: Employee }
implements (interface)impl Trait for Typeimpl Drawable for Circle
Method overridingTrait implementationEach type provides its own
OOPRustNotes
super callExplicit delegationself.inner.method()
Virtual methodTrait object method&dyn Trait for dynamic dispatch
Non-virtual methodGeneric with trait boundfn draw<T: Drawable>(item: &T)
Multiple inheritanceMultiple trait boundsT: Read + Write + Seek
Abstract methodTrait method without defaultMust be implemented

Access control

OOPRustNotes
publicpubVisible everywhere
private(default)Visible in current module only
protectedpub(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

PatternRust approach
Singletonstatic with OnceLock or lazy_static
PatternRust approach
FactoryAssociated function returning Self or Box<dyn Trait>
BuilderStruct with chainable methods returning Self
StrategyTrait object (Box<dyn Strategy>) or enum
ObserverChannels (mpsc) or callback closures
DecoratorWrapper struct implementing same trait
AdapterNewtype pattern with trait implementation
Template MethodTrait with default methods calling required methods
Null ObjectOption<T> or dedicated unit struct
RAIIDefault behavior (Drop trait)

Type system mappings

OOPRustExample
Generic classGeneric structstruct Container<T> { item: T }
Generic methodGeneric functionfn process<T: Clone>(item: T)
Bounded genericTrait bounds<T: Display + Debug>
Wildcard (?)impl Trait or dyn Traitfn print(item: &dyn Display)
CovariancePhantom types, limitedComplex topic
OOPRustExample
Enum (Java/C#)enum (much more powerful)Variants can hold data
Nullable typeOption<T>Option<String>
ExceptionResult<T, E>Result<Data, Error>
Try-catchmatch or ? operatorfile.read()?.parse()?
Checked exceptionResult in signaturePart of function type

Quick syntax reference

Java / C#Rust
class Foo {}struct Foo {} + impl Foo {}
interface Bar {}trait Bar {}
class Foo implements Barimpl Bar for Foo
Foo foo = new Foo()let foo = Foo::new()
foo.method()foo.method()
Foo.staticMethod()Foo::static_method()
foo instanceof BarPattern 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)