Rust•Traits
Rust Traits: Shared Behavior and Polymorphism
Rust uses traits instead of classical inheritance, defining shared capability contracts across types.
Syntax
trait Describable {
fn describe(&self) -> String;
}
Parameters & Values
Key components and acceptable values for this structure:
| Parameter | Type | Description |
|---|---|---|
| trait | Keyword | Defines shared behavior contract. |
Ready-to-Run Code Example
Executable in CompilraRun this complete, working example directly without installing Rust locally:
trait HealthChecker {
fn check_health(&self) -> String;
}
struct DatabaseNode {
name: String,
active_conns: u32,
}
impl HealthChecker for DatabaseNode {
fn check_health(&self) -> String {
format!("{}: OK ({} active connections)", self.name, self.active_conns)
}
}
// Function accepting generic type bounded by trait
fn run_diagnostic<T: HealthChecker>(item: &T) {
println!("[DIAGNOSTIC] {}", item.check_health());
}
fn main() {
let db = DatabaseNode {
name: String::from("PostgresCluster"),
active_conns: 42,
};
run_diagnostic(&db);
}Expected Output:
[DIAGNOSTIC] PostgresCluster: OK (42 active connections)
How It Works: Step-by-Step
- Lines 1-3: Defines trait HealthChecker.
- Lines 10-14: Implements trait for DatabaseNode.
- Lines 17-19: Generic function uses trait bound <T: HealthChecker> for static monomorphization.
Key Concepts
- Traits in Rust replace interfaces and abstract base classes.
- Trait bounds generate monomorphized zero-cost code at compile time.
- Dynamic dispatch is achieved using trait objects: &dyn Trait.
Common Mistake: Trying to inherit fields from a base struct
Rust does not have struct inheritance. Use composition (embedding one struct inside another) and traits.
❌ Incorrect
struct Child : Parent { ... } // Syntax Error!✅ Correct
struct Child { parent_data: Parent, extra: u32 }Related Rust Tutorials & Compiler
Rust Structs and impl Blocks: Methods and Associated Functions
Define methods on structs with impl blocks and associated functions (constructors).
Rust Functions and Implicit Expression Block Return Optimization
Master Rust expression-oriented functions: implicit tail returns (omitting semicolon), explicit return keyword, and block optimization schemas.
Rust Error Handling: Result, Option, and the Question Mark (?) Operator
Master idiomatic error handling in Rust using Result<T, E> and the propagation operator (?).
Rust Online Compiler
Open in Compilra IDE
Run and test Rust on Compilra
Execute this code snippet with pre-supplied standard input (stdin) in Compilra’s cloud compiler.