The Translation Guide
local graph
Chapter 16 — The Translation Guide
Section titled “Chapter 16 — The Translation Guide”Verbum pro verbo. (Word for word.)
Design patterns in object-oriented languages rely on specific language features: abstract classes, interfaces, protected visibility, virtual methods, and inheritance hierarchies. Rust provides none of these in their traditional form. Yet every concept that these features express has a Rust equivalent, often cleaner and more explicit than the original. This chapter provides a systematic mapping from OOP constructs to Rust idioms, serving as a reference for developers translating existing designs or thinking through new ones.
The mappings here are not mechanical substitutions. Each OOP construct exists to solve a problem, and Rust often solves that problem differently. Understanding the underlying intent reveals which Rust mechanism best captures it. The goal is not to write Java in Rust syntax but to express the same design intent using Rust’s tools in their natural way.
Abstract class to trait with default methods and struct
Abstract classes in OOP serve two purposes simultaneously: they define a contract (methods that subclasses must implement) and provide partial implementation (methods that subclasses inherit). This combination creates convenience at the cost of coupling. A change to the abstract class ripples through all subclasses. A subclass cannot inherit from multiple abstract classes in most languages. The partial implementation and the contract are forever intertwined, even when they could usefully vary independently.
Rust separates these concerns explicitly. The contract becomes a trait. The shared data becomes a struct that types can embed. The partial implementation becomes default methods in traits or methods on the embedded struct. This separation requires more explicit wiring but enables more flexible designs. Each piece can evolve independently, and types can mix and match components as needed.
This separation also clarifies thinking during design. When creating an abstract class, developers often blur the line between “what must subclasses provide” and “what do subclasses typically need.” Rust forces that distinction: traits define requirements, structs hold shared data, and default methods provide convenience without mandating structure.
Consider an abstract class for document exporters in Java. The DocumentExporter base class holds a filename field, provides a constructor, and defines an export method that calls format (abstract) and writeToFile (has default implementation). A PdfExporter subclass extends this, calling the parent constructor and overriding format with PDF-specific logic. The abstract class provides structure (the export template method), requires subclass input (format), and offers overridable defaults (writeToFile).
Translating this to Rust separates the shared data, required behavior, and default implementations:
pub struct ExporterConfig { pub filename: String,}
pub trait DocumentFormatter { fn format(&self, doc: &Document) -> String;}pub trait FileWriter { fn write_to_file(&self, config: &ExporterConfig, content: &str) -> io::Result<()> { fs::write(&config.filename, content) }}
pub struct DocumentExporter<F> { config: ExporterConfig, formatter: F,}
impl<F: DocumentFormatter + FileWriter> DocumentExporter<F> { pub fn new(filename: impl Into<String>, formatter: F) -> Self { Self { config: ExporterConfig { filename: filename.into() }, formatter, } }
pub fn export(&self, doc: &Document) -> io::Result<()> { let content = self.formatter.format(doc); self.formatter.write_to_file(&self.config, &content) }}The shared data lives in ExporterConfig. Required behavior is the DocumentFormatter trait. Default implementation comes from FileWriter, which provides a default write_to_file that implementors can override. Concrete exporters implement these traits:
pub struct PdfFormatter;
impl DocumentFormatter for PdfFormatter { fn format(&self, doc: &Document) -> String { // PDF-specific formatting format!("PDF: {}", doc.content) }}impl FileWriter for PdfFormatter { // Uses default write_to_file}The Rust version has more pieces, but each piece has a single responsibility. The formatter can be tested independently of file operations. The configuration can be shared or varied. A custom file writer (perhaps writing to cloud storage) requires implementing only FileWriter, not subclassing an abstract class.
This decomposition pays dividends during testing. In the OOP version, testing the export logic requires either mocking file system operations or accepting that tests write actual files. The Rust version allows injecting a test formatter or a test file writer independently. Unit tests can verify formatting without touching the filesystem, and integration tests can verify file writing with known content.
The verbosity concerns developers accustomed to abstract classes, where inheritance provides implicit wiring. In practice, the explicit wiring in Rust is written once and rarely revisited. The flexibility it provides, the ability to swap components, test in isolation, and evolve pieces independently, outweighs the initial setup cost. Large codebases benefit especially, where abstract class hierarchies tend to calcify into structures that resist modification.
Interface to trait
Interfaces in OOP represent pure contracts: a set of method signatures that implementing classes must provide. They carry no implementation and no state. This purity makes interfaces the most portable OOP concept; they translate almost directly to traits in Rust.
Both interfaces and traits define contracts without implementation (though both can provide default implementations in modern versions). Both enable polymorphism: code can accept any type satisfying the contract without knowing the concrete type. Both allow a single type to implement multiple contracts. The conceptual alignment makes this translation straightforward.
The syntactic differences are minor. A Java interface declaring void print() and int pageCount() becomes a Rust trait declaring fn print(&self) and fn page_count(&self) -> usize. The method signatures are nearly identical aside from Rust’s explicit &self receiver (where Java’s this is implicit) and Rust’s snake_case naming convention.
The semantic differences emerge in the details. Rust traits can have default method implementations, making them more flexible than traditional Java interfaces (though Java 8+ added default methods, bringing them closer to Rust traits). Rust traits can declare associated types, which act as placeholders for types that are chosen by each implementation of the trait. This allows the trait to express relationships between types without requiring them to be generic parameters. Traits may also define associated constants, which are compile-time values that every implementation must provide. Together, these features make traits more than just collections of method signatures, enabling them to encode richer and more precise abstractions.
The most significant difference is structural: trait implementations are separate from type definitions. In Java or C#, a class declares which interfaces it implements at definition time. In Rust, impl Trait for Type blocks can appear anywhere in the crate that defines the type (or, with restrictions, the trait). This separation means implementations can be organized by concern rather than by type, and external traits can be implemented for existing types without modifying those types.
Implementing an interface becomes implementing a trait:
trait Printable { fn print(&self); fn page_count(&self) -> usize;}
pub struct Report { content: String, pages: usize,}
impl Printable for Report { fn print(&self) { println!("{}", self.content); }
fn page_count(&self) -> usize { self.pages }}
pub struct Invoice { items: Vec<LineItem>,}
impl Printable for Invoice { fn print(&self) { for item in &self.items { println!("{}: ${:.2}", item.description, item.amount); } }
fn page_count(&self) -> usize { (self.items.len() / 20) + 1 }}
// Function accepting any Printablefn print_document(doc: &impl Printable) { println!("Document has {} pages", doc.page_count()); doc.print();}The struct definition declares data; the impl block declares behavior. This separation keeps type definitions focused while allowing behavior to be added incrementally.
Unlike OOP interfaces, trait implementations are separate from struct definitions. This enables implementing traits for types defined elsewhere (subject to orphan rules) and keeps type definitions focused on data while behavior spreads across impl blocks.
The orphan rules deserve mention because they constrain what would otherwise be unlimited flexibility. A crate can implement a trait for a type only if it defines either the trait or the type (with some nuances around generic parameters). This restriction prevents conflicting implementations from different crates and ensures that adding a dependency cannot change how existing code behaves. The rules occasionally require newtype wrappers to implement external traits for external types, a minor inconvenience for significant safety.
Multiple inheritance to multiple trait bounds
Multiple inheritance has a troubled history in programming language design. Languages that support it (C++, Python) provide power at the cost of complexity. The diamond problem, where a class inherits from two classes that share a common ancestor, creates ambiguity about which implementation to use. Method resolution order in Python and virtual inheritance in C++ address these issues, but the solutions add cognitive overhead that simpler inheritance models avoid.
Languages that prohibit multiple class inheritance (Java, C#) typically allow implementing multiple interfaces while inheriting implementation from a single class. This split acknowledges that combining interfaces is valuable while combining implementations is problematic. The distinction between interface inheritance and implementation inheritance proves more fundamental than it first appears.
Rust handles interface combination through trait bounds without any of multiple inheritance’s complications. A type can implement any number of traits. Functions can require any combination of traits through bounds. No ambiguity arises because traits define contracts, not implementations (default methods notwithstanding). When a type implements multiple traits with same-named methods, the caller specifies which trait’s method to invoke using fully qualified syntax.
Consider three traits: Readable with a read method, Writable with a write method, and Seekable with a seek method:
pub trait Readable { fn read(&mut self, buf: &mut [u8]) -> io::Result<usize>;}
pub trait Writable { fn write(&mut self, buf: &[u8]) -> io::Result<usize>;}
pub trait Seekable { fn seek(&mut self, pos: SeekFrom) -> io::Result<u64>;}
// Function requiring multiple traitspub fn copy_section<T>( stream: &mut T, start: u64, length: usize, output: &mut Vec<u8>,) -> io::Result<()>where T: Readable + Seekable,{ stream.seek(SeekFrom::Start(start))?; let mut buffer = vec![0u8; length]; stream.read(&mut buffer)?; output.extend(buffer); Ok(())}
// A type implementing all three traitspub struct MemoryBuffer { data: Vec<u8>, position: usize,}
impl Readable for MemoryBuffer { fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> { let available = self.data.len() - self.position; let to_read = buf.len().min(available); buf[..to_read].copy_from_slice(&self.data[self.position..self.position + to_read]); self.position += to_read; Ok(to_read) }}
impl Writable for MemoryBuffer { fn write(&mut self, buf: &[u8]) -> io::Result<usize> { self.data.extend_from_slice(buf); Ok(buf.len()) }}
impl Seekable for MemoryBuffer { fn seek(&mut self, pos: SeekFrom) -> io::Result<u64> { self.position = match pos { SeekFrom::Start(n) => n as usize, SeekFrom::Current(n) => (self.position as i64 + n) as usize, SeekFrom::End(n) => (self.data.len() as i64 + n) as usize, }; Ok(self.position as u64) }}The bound T: Readable + Seekable expresses that T must implement both traits. Any type satisfying these bounds works with the function. This achieves what multiple inheritance achieves for interfaces without inheriting any implementation. The syntax scales to any number of traits: T: A + B + C + D requires all four. Supertraits (traits that require other traits) can bundle common combinations, so trait ReadWrite: Readable + Writable {} lets code require T: ReadWrite instead of repeating the bounds.
When multiple inheritance would share implementation (the more problematic case), Rust uses composition. Rather than inheriting methods from multiple parents, a type contains instances of components and delegates to them:
// Components providing reusable functionalitypub struct Logger { prefix: String,}
impl Logger { pub fn new(prefix: &str) -> Self { Logger { prefix: prefix.to_string() } }
pub fn log(&self, message: &str) { println!("[{}] {}", self.prefix, message); }}
pub struct Metrics { counters: HashMap<String, u64>,}
impl Metrics { pub fn new() -> Self { Metrics { counters: HashMap::new() } }
pub fn increment(&mut self, name: &str) { *self.counters.entry(name.to_string()).or_insert(0) += 1; }
pub fn get(&self, name: &str) -> u64 { *self.counters.get(name).unwrap_or(&0) }}
// Type composing both componentspub struct Service { logger: Logger, metrics: Metrics, name: String,}
impl Service { pub fn new(name: &str) -> Self { Service { logger: Logger::new(name), metrics: Metrics::new(), name: name.to_string(), } }
pub fn handle_request(&mut self, request: &Request) -> Response { self.logger.log(&format!("Handling request: {:?}", request)); self.metrics.increment("requests"); let response = self.process(request);
if response.is_error() { self.metrics.increment("errors"); } response }
fn process(&self, request: &Request) -> Response { // Implementation Response::ok() }}This explicit delegation avoids the ambiguity of multiple inheritance while achieving the same code reuse.
The explicitness that composition requires often reveals design issues that inheritance obscures. When delegation becomes tedious, it suggests that the component boundaries might be wrong or that a different abstraction would serve better. Inheritance’s implicit method resolution hides this friction, allowing questionable designs to persist longer before their costs become apparent.
The following diagram shows how OOP multiple inheritance maps to Rust traits and composition:
graph LR
subgraph OOP["OOP Multiple Inheritance"]
PA["Parent A<br/>+ methodA()"] --> CH["Child"]
PB["Parent B<br/>+ methodB()"] --> CH
end
subgraph RUST["Rust Equivalent"]
TA["trait A<br/>+ method_a()"] -- implements --> IM["struct Impl<br/>impl A for Impl<br/>impl B for Impl"]
TB["trait B<br/>+ method_b()"] -- implements --> IM
end
[!visual-conversion] Multiple inheritance becomes multiple trait implementations. Print diagram (PDF 441, printed p. 433) of two stacked frames recreated in Mermaid; labels verbatim (the first frame’s title, partly hidden behind the Parent A box in print, reads “OOP Multiple [Inheri]tance”).
Protected members to pub(crate) or pub(super)
Protected visibility in OOP serves a specific need: exposing implementation details to subclasses while hiding them from other code. A base class might have a helper method that subclasses need to call or override but that external code should not access. Protected members form part of the contract between a class and its descendants, distinct from the public contract with all users.
Since Rust has no inheritance, it has no protected visibility in the OOP sense. There are no descendants to protect things for. However, the underlying need remains: some code should access certain members while other code should not. Rust addresses this through module-based visibility rather than hierarchy-based visibility.
The shift from hierarchy-based to module-based visibility requires rethinking encapsulation boundaries. In OOP, the boundary follows the inheritance tree: a class and its descendants form a trust group. In Rust, the boundary follows the module tree: a module and its contents form a trust group. This difference aligns with how Rust code is actually organized, where modules group related functionality regardless of type relationships.
When “protected” means “available within this library but not to external users,” pub(crate) provides that visibility:
// In src/network/connection.rspub struct Connection { // Public to crate, hidden from external users pub(crate) socket: TcpStream, pub(crate) buffer: Vec<u8>,
// Fully private state: ConnectionState,}
impl Connection { // Public API pub fn send(&mut self, data: &[u8]) -> io::Result<()> { self.validate_state()?; self.raw_write(data) }
// Available within crate for advanced use pub(crate) fn raw_write(&mut self, data: &[u8]) -> io::Result<()> { self.socket.write_all(data) }
// Private implementation detail fn validate_state(&self) -> io::Result<()> { match self.state { ConnectionState::Connected => Ok(()), _ => Err(io::Error::new(io::ErrorKind::NotConnected, "not connected")), } }}
// In src/network/pool.rs - can access pub(crate) membersimpl ConnectionPool { fn health_check(&self, conn: &mut Connection) -> bool { // Can access raw_write because we're in the same crate conn.raw_write(&[0]).is_ok() }}When “protected” means “available to this module and its children,” pub(super) limits visibility to the parent module. A method marked pub(super) on a type in network::connection would be accessible from the network module but not from network::connection::internal or from outside network. This granularity allows precise control over what code can access implementation details.
The pub(in path) syntax provides even more specific control, restricting visibility to a named ancestor module. These visibility modifiers compose with Rust’s module structure to create encapsulation boundaries that match the actual code organization rather than an inheritance hierarchy that might not exist.
For more complex visibility requirements, combining modules with re-exports creates custom boundaries. The key insight is that Rust’s visibility is module-based rather than class-based, which changes how encapsulation boundaries are drawn.
I have found that thinking in terms of “what modules should access this” rather than “what subclasses should access this” leads to cleaner designs. Module boundaries often align better with actual code organization than class hierarchies do.
Virtual dispatch to trait objects
Virtual methods in OOP enable runtime polymorphism: a base class reference can point to any subclass, and method calls dispatch to the actual type’s implementation at runtime. This mechanism underlies much of OOP’s power. A drawing function can iterate over shapes without knowing whether each shape is a circle, rectangle, or custom user-defined type. The correct draw implementation executes for each shape without conditional logic in the drawing function.
The runtime cost of virtual dispatch is a vtable lookup: an indirect function call through a pointer stored in the object or associated with its type. This cost is small but not zero, and it prevents certain compiler optimizations like inlining. Languages like C++ distinguish virtual from non-virtual methods precisely to let developers choose when to pay this cost.
Rust makes the choice between static and dynamic dispatch explicit and defaults to static. When a function takes impl Trait or uses generic bounds, the compiler generates specialized code for each concrete type used. When a function takes dyn Trait, it uses dynamic dispatch through a vtable, matching OOP’s virtual method behavior. This explicitness helps developers understand performance characteristics and choose appropriately.
Trait objects, written as dyn Trait, provide Rust’s equivalent of virtual dispatch. A trait object is a fat pointer containing two pointers: one to the data and one to a vtable of method implementations. This structure allows the same calling code to invoke methods on any type implementing the trait, with dispatch resolved at runtime.
Consider a graphics system with virtual draw methods. In C++, a
Shape base class declares a pure virtual draw method. Circle and
Rectangle inherit from Shape and override draw with their
implementations. A renderAll function iterates over
vector<Shape*>, calling draw on each element without knowing or
caring about the concrete types. The virtual dispatch mechanism
routes each call to the appropriate implementation.
The Rust equivalent uses trait objects:
pub trait Shape { fn draw(&self, canvas: &mut Canvas); fn area(&self) -> f64;}
pub struct Circle { center: Point, radius: f64,}
impl Shape for Circle { fn draw(&self, canvas: &mut Canvas) { canvas.draw_circle(self.center, self.radius); }
fn area(&self) -> f64 { std::f64::consts::PI * self.radius * self.radius }}
pub struct Rectangle { top_left: Point, width: f64, height: f64,}impl Shape for Rectangle { fn draw(&self, canvas: &mut Canvas) { canvas.draw_rect(self.top_left, self.width, self.height); }
fn area(&self) -> f64 { self.width * self.height }}
// Function using dynamic dispatchpub fn render_all(shapes: &[Box<dyn Shape>], canvas: &mut Canvas) { for shape in shapes { shape.draw(canvas); // Virtual dispatch through vtable }}
// Heterogeneous collectionlet shapes: Vec<Box<dyn Shape>> = vec![ Box::new(Circle { center: Point(0.0, 0.0), radius: 5.0 }), Box::new(Rectangle { top_left: Point(10.0, 10.0), width: 20.0, height: 15.0 }),];The dyn Shape syntax indicates a trait object with dynamic dispatch.
Box<dyn Shape> is an owned trait object, allocated on the heap. The
vector can hold circles, rectangles, and any other type implementing
Shape, dispatching to the correct implementation at runtime.
Trait objects have restrictions that virtual methods do not. The trait must be “object safe,” meaning its methods cannot use Self in certain ways that require knowing the concrete type at compile time. Methods returning Self or taking Self by value prevent object safety because the size of Self varies between implementations. Generic methods similarly prevent object safety because the vtable cannot represent an unbounded set of instantiations. These restrictions occasionally require redesigning traits intended for dynamic dispatch, splitting methods that prevent object safety into separate traits.
The choice between generics and trait objects involves trade-offs beyond performance. Generics produce larger binaries (each instantiation generates code) but enable inlining and type-specific optimization. Trait objects produce smaller binaries (one copy of the code) but incur dispatch overhead and prevent inlining. Generics reveal concrete types at compile time, enabling additional bounds and operations. Trait objects hide concrete types, which can be desirable for encapsulation or necessary when types are determined at runtime.
In practice, I reach for generics by default and use trait objects when heterogeneous collections are needed or when reducing binary size matters. The explicit choice forces thinking about which scenarios the code must support, often leading to clearer designs than OOP’s implicit virtual dispatch.
The following diagram contrasts static and dynamic dispatch in Rust:
graph LR
subgraph SD["Static Dispatch (Generics)"]
G["fn draw#lt;T: Shape#gt;(s: &T)"] --> GC["draw::#lt;Circle#gt;"]
G --> GR["draw::#lt;Rectangle#gt;"]
end
subgraph DD["Dynamic Dispatch (dyn Trait)"]
D["fn draw(s: &dyn Shape)"] --> V["vtable lookup<br/>at runtime"]
V --> DC["Circle::draw"]
V --> DR["Rectangle::draw"]
end
[!visual-conversion] Generics generate specialized code at compile time; trait objects dispatch through vtables at runtime. Print diagram (PDF 447, printed p. 439) of two stacked frames recreated in Mermaid; labels verbatim (the second frame’s title is partly hidden behind a box in print: “Dynamic Dispatch (dyn [Trait])”).
Template method to traits with provided methods
The Template Method pattern defines an algorithm’s skeleton in a base class, deferring some steps to subclasses. The base class implements the overall structure while subclasses customize specific steps. This pattern appears frequently in frameworks and libraries, where the framework controls the high-level flow and applications provide the specifics.
The pattern embodies the Hollywood Principle: “don’t call us, we’ll call you.” The base class calls subclass methods at appropriate points rather than subclasses calling base class methods. This inversion of control makes frameworks possible: the framework defines when things happen, and applications define what happens.
In OOP, template methods are typically final (non-overridable) methods that call abstract or virtual methods. The template method itself should not be overridden because it defines the algorithm structure. The hook methods (the steps that subclasses customize) are abstract when subclasses must provide them and virtual with default implementations when customization is optional.
Rust translates this pattern using traits with a mix of required and provided methods. Required methods (those without implementations) force implementors to provide specific behavior. Provided methods (those with default implementations) can be overridden when needed. The template method is a provided method that calls both required and other provided methods, orchestrating the algorithm.
A key difference from OOP: Rust’s provided methods can be overridden by implementors, whereas OOP’s final methods cannot. Rust has no mechanism to prevent overriding a default method. If preventing override is essential, the method can be defined on a struct rather than a trait, with the trait providing the customization points. In practice, the documentation’s intent (“do not override this method”) usually suffices.
In OOP, a DataProcessor abstract class might have a final process method (the template) that calls validate, transform, save, and notifyComplete in sequence. The validate and transform methods are abstract, forcing subclasses to provide implementations. The save and notifyComplete methods have default implementations that subclasses can override if needed. The final modifier on process prevents subclasses from changing the algorithm structure.
The Rust translation uses a trait where the template method has a default implementation calling required methods:
pub trait DataProcessor { // Required methods - must be implemented fn validate(&self, data: &Data) -> Result<(), ValidationError>; fn transform(&self, data: Data) -> Data;
// Provided methods - can be overridden fn save(&self, data: &Data) -> io::Result<()> { // Default implementation self.default_save(data) }
fn notify_complete(&self) { println!("Processing complete"); }
// Template method - orchestrates the algorithm fn process(&self, data: Data) -> Result<(), ProcessError> { self.validate(&data)?; let transformed = self.transform(data); self.save(&transformed)?; self.notify_complete(); Ok(()) }}Implementors provide the required methods and optionally override the provided ones. A JsonProcessor might implement validate using a schema validator and transform to convert data to canonical form, accepting the default save and notify_complete implementations. An XmlProcessor might implement the required methods differently and also override save to write to a specific destination path instead of using the default database. Each implementor customizes exactly the parts it needs while inheriting the algorithm structure from the trait’s process method.
The pattern translates cleanly. Default implementations in traits serve the same role as non-abstract methods in abstract classes. Required methods (those without defaults) serve as abstract methods. The template method itself can have a default implementation that orchestrates the algorithm.
The Rust version gains flexibility the OOP version lacks. Different types can implement the trait with different combinations of overrides. A type can implement multiple traits, each with its own template method, combining algorithms that OOP would require multiple inheritance or awkward delegation to achieve. The trait can be implemented for existing types, retrofitting them with new algorithmic frameworks without modifying their definitions.
Error handling in template methods deserves attention. The OOP version typically uses exceptions, allowing any step to fail and unwind the algorithm. The Rust version uses Result, requiring explicit propagation with ?. This explicitness ensures that failure modes are considered: what happens if validation fails? Should transformation proceed if save fails? The types force answers to these questions rather than letting exceptions implicitly handle them.
Quick reference table
The translations covered in this chapter form a reference for common OOP-to-Rust mappings. Each entry identifies the OOP concept, its Rust equivalent, and when alternatives might apply:
| OOP concept | Rust equivalent | Notes |
|---|---|---|
| Abstract class | Trait + struct for shared data | Separate behavior contract from data storage |
| Interface | Trait | Direct mapping; Rust traits can also have defaults |
| Concrete class | Struct + impl blocks | Data and behavior separated syntactically |
| Class inheritance | Composition or trait reuse | Embed components; no method inheritance |
| Multiple inheritance | Multiple trait bounds | T: TraitA + TraitB + TraitC |
| Protected members | pub(crate) or pub(super) | Module-based rather than hierarchy-based |
| Virtual methods | dyn Trait (trait objects) | Runtime dispatch through vtable |
| Non-virtual methods | Generic bounds or direct impl | Static dispatch by default |
| Template method | Trait with default methods | Default impl calls required methods |
| final class | No special handling needed | Types cannot be “extended” in Rust |
| final method | Default in traits (cannot be overridden differently) | Implementors cannot change provided methods |
| static methods | Associated functions (impl Type { fn foo() {} }) | No self parameter |
| Constructor | Associated function (fn new()) | Convention, not language feature |
| Destructor | Drop trait | Called automatically when value goes out of scope |
| this/self | &self, &mut self, or self | Explicit receiver in method signatures |
| instanceof | Pattern matching or Any trait | Prefer exhaustive matching over type checks |
The table provides quick lookups, but the preceding sections offer the context needed to choose appropriately. A direct translation is not always the best translation; understanding what the OOP code intended to achieve often suggests a more idiomatic Rust design.
Patterns that disappear
Section titled “Patterns that disappear”Some OOP constructs have no Rust equivalent because Rust’s design eliminates the problems they address. Understanding these disappearances prevents searching for translations that do not exist and highlights how Rust’s foundations differ from OOP’s.
The Null Object pattern provides a do-nothing implementation to avoid null checks. In OOP, methods might return null, requiring callers to check before using the result. The Null Object pattern supplies an object that responds to all methods with no-op behavior, allowing code to treat null and non-null cases uniformly. Rust’s Option type makes absence explicit at the type level. Pattern matching forces handling both Some and None cases. The compiler rejects code that ignores the possibility of absence. What required a design pattern in OOP becomes unnecessary when the type system expresses optionality directly.
Defensive copying addresses a fundamental OOP concern: when multiple references point to mutable data, changes through one reference affect all others. OOP code often clones objects before storing or returning them to prevent unexpected mutations. The clone creates an independent copy that modifications cannot affect. Rust’s ownership and borrowing rules eliminate this concern at compile time. A mutable reference guarantees exclusive access; no other code can observe the data while the reference exists. Shared references guarantee immutability; multiple readers cannot interfere because none can write. What required runtime cloning as a defensive measure becomes unnecessary when the compiler enforces access discipline.
Getter and setter methods encapsulate fields in OOP, allowing classes to control access and validate changes. A setter might check that values fall within valid ranges or maintain invariants across multiple fields. In Rust, public fields are acceptable when mutation is harmless. When invariants exist, the type system often expresses them directly: a NonZeroU32 cannot be zero by construction, not by setter validation. When validation is needed, constructors that return Result or builder patterns provide it once at creation rather than on every modification. The pervasive getters and setters of OOP often reflect defensive programming that Rust’s types render unnecessary.
The Singleton pattern ensures a class has exactly one instance with global access. OOP uses private constructors and static accessor methods to enforce uniqueness. The pattern addresses both instance control and global access, concerns that sometimes should be separated. Rust provides static items for global access and OnceCell or lazy_static for lazy initialization. However, the need for singletons often indicates design issues. Global mutable state complicates testing and concurrency. Function parameters and dependency injection make dependencies explicit and code more flexible. When translating singletons, I recommend questioning whether global state is truly necessary rather than mechanically reproducing the pattern.
Reference Summary
Translating OOP constructs to Rust requires understanding the intent behind each construct and matching it to Rust’s mechanisms.
Abstract classes split into traits for behavior contracts and structs for shared data. Default method implementations provide inherited behavior without inheritance hierarchies.
Interfaces map directly to traits. Multiple interface implementation becomes multiple trait implementations on a single type.
Multiple inheritance becomes multiple trait bounds for interfaces and composition for implementation sharing. Rust avoids the complexity of multiple inheritance while achieving the same capabilities.
Protected visibility becomes module-based visibility through
pub(crate) and pub(super), aligning with Rust’s module-centric
encapsulation model.
Virtual dispatch translates to trait objects (dyn Trait) when runtime polymorphism is needed, with generics providing static dispatch as the default.
The Template Method pattern uses traits with default implementations that call required methods, cleanly separating the algorithm skeleton from customization points.
Some patterns disappear entirely because Rust’s design eliminates the problems they solved in OOP contexts.
These translations form a vocabulary for thinking about OOP designs in Rust terms. The next part of the book moves to concurrency, where Rust’s ownership model provides safety guarantees that OOP languages achieve only through discipline and runtime checks.