Rust:Rust Traits: Shared Behavior and Polymorphism
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:

ParameterTypeDescription
traitKeywordDefines shared behavior contract.

Ready-to-Run Code Example

Executable in Compilra

Run 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

Run and test Rust on Compilra

Execute this code snippet with pre-supplied standard input (stdin) in Compilra’s cloud compiler.

Rust Online Compiler