{
    "slug": "rust_traits",
    "term": "Rust Traits",
    "category": "rust",
    "difficulty": "intermediate",
    "short": "Traits define shared behavior that types opt into explicitly, enabling polymorphism through composition rather than class inheritance.",
    "long": "A trait in Rust is a named set of method signatures (and optional default implementations) that describes behavior a type can provide. Traits are Rust's primary tool for abstraction and polymorphism, filling the role that interfaces and abstract base classes play in other languages, but with important differences. A type gains a trait's behavior only by an explicit `impl Trait for Type` block; there is no inheritance hierarchy and no implicit `is-a` relationship. This makes capabilities composable: a single type can implement dozens of unrelated traits, and you add behavior by implementing more traits rather than extending a base class.\n\nTraits enable two kinds of polymorphism. Static dispatch uses generics with trait bounds, such as `fn print<T: Display>(x: T)`, where the compiler monomorphizes a specialized copy per concrete type with zero runtime cost. Dynamic dispatch uses trait objects like `Box<dyn Display>` or `&dyn Display`, which store a pointer to data plus a vtable, resolving method calls at runtime in exchange for a small indirection cost and a heap-allocated or borrowed object. Choosing between them is a deliberate trade-off, not a default.\n\nDefault methods let a trait supply implementations that any implementor inherits unless it overrides them, which is the closest Rust gets to shared code reuse. Traits can also require other traits via supertraits (`trait Ord: PartialOrd`), declare associated types and constants, and be implemented generically with blanket impls like `impl<T: Display> ToString for T`.\n\nThe orphan rule constrains where you may write an impl: either the trait or the type must be defined in your crate. This prevents two crates from defining conflicting implementations for the same trait and type. The newtype pattern (wrapping a foreign type in a local struct) is the standard workaround when you need to implement a foreign trait for a foreign type.\n\nObject safety governs which traits can become trait objects: methods returning `Self` or using generic type parameters generally break `dyn` compatibility. Understanding traits means understanding explicit implementation, static versus dynamic dispatch, default methods, the orphan rule, and object safety - none of which map cleanly onto classical inheritance.",
    "aliases": [
        "rust trait",
        "trait bounds",
        "dyn trait"
    ],
    "tags": [
        "rust",
        "traits",
        "polymorphism",
        "generics",
        "dynamic-dispatch",
        "composition"
    ],
    "misconception": "Traits work like class inheritance where a type automatically gains behavior from a base. In reality a type gains a trait only through an explicit impl block, and traits compose freely rather than forming a single hierarchy.",
    "why_it_matters": "Treating traits as inheritance leads to fighting the borrow checker, misusing trait objects, and hitting orphan-rule or object-safety errors that confuse engineers coming from OOP languages.",
    "common_mistakes": [
        "Assuming a type inherits a trait implicitly instead of writing an explicit impl Trait for Type block.",
        "Reaching for Box<dyn Trait> dynamic dispatch when a generic with a trait bound would be zero-cost.",
        "Trying to implement a foreign trait for a foreign type and hitting the orphan rule instead of using a newtype wrapper.",
        "Designing a trait with methods returning Self or generic parameters, then being unable to use it as a dyn trait object.",
        "Forgetting to bring a trait into scope with `use`, so its methods appear missing on a type that does implement it."
    ],
    "when_to_use": [
        "Defining shared behavior that several unrelated types should implement, such as serialization or comparison.",
        "Writing generic functions and containers that operate over any type satisfying a bound, getting zero-cost static dispatch.",
        "Providing default method implementations so implementors share code without an inheritance hierarchy.",
        "Decoupling a module from concrete types by programming against a trait for testability and substitution."
    ],
    "avoid_when": [
        "You need to store a heterogeneous collection of different concrete types behind one interface, where a generic single-type bound cannot express it and dyn is the right tool.",
        "Adding a trait abstraction for a single concrete implementation that will never have a second one, which is premature generality.",
        "The behavior is genuinely data-specific and forcing it behind a shared trait would create a leaky or meaningless abstraction."
    ],
    "related": [
        "rust_async_await",
        "typescript_interfaces_types",
        "single_responsibility"
    ],
    "prerequisites": [
        "single_responsibility"
    ],
    "refs": [
        "https://doc.rust-lang.org/book/ch10-02-traits.html",
        "https://doc.rust-lang.org/reference/items/traits.html",
        "https://doc.rust-lang.org/reference/items/implementations.html#trait-implementation-coherence",
        "https://doc.rust-lang.org/reference/items/traits.html#object-safety"
    ],
    "bad_code": "use std::fmt::Display;\n\n// Forcing dynamic dispatch and heap allocation where generics would do.\nstruct Logger {\n    sinks: Vec<Box<dyn Display>>,\n}\n\nfn print_all(items: Vec<Box<dyn Display>>) {\n    for item in items {\n        // Runtime vtable indirection on every call, even when types are known.\n        println!(\"{}\", item);\n    }\n}\n\nfn main() {\n    // Every value must be boxed on the heap just to satisfy the API.\n    let logger = Logger {\n        sinks: vec![Box::new(1), Box::new(\"hi\")],\n    };\n    print_all(logger.sinks);\n}",
    "good_code": "use std::fmt::Display;\n\n// Static dispatch via a trait bound: zero-cost, monomorphized per type.\nfn print_one<T: Display>(item: T) {\n    println!(\"{}\", item);\n}\n\n// A default method gives shared behavior without inheritance.\ntrait Describe {\n    fn name(&self) -> String;\n    fn describe(&self) -> String {\n        format!(\"This is {}\", self.name())\n    }\n}\n\nstruct Widget;\n\n// Behavior is opted into explicitly.\nimpl Describe for Widget {\n    fn name(&self) -> String {\n        \"a widget\".to_string()\n    }\n}\n\nfn main() {\n    print_one(1);\n    print_one(\"hi\");\n    println!(\"{}\", Widget.describe());\n}",
    "quick_fix": "Add an explicit `impl Trait for Type` block, prefer generic trait bounds over Box<dyn Trait> unless you need runtime heterogeneity, and wrap foreign types in a newtype to satisfy the orphan rule.",
    "severity": "low",
    "effort": "medium",
    "created": "2026-06-05",
    "updated": "2026-06-05",
    "citation": {
        "canonical_url": "https://codeclaritylab.com/glossary/rust_traits",
        "html_url": "https://codeclaritylab.com/glossary/rust_traits",
        "json_url": "https://codeclaritylab.com/glossary/rust_traits.json",
        "source": "CodeClarityLab Glossary",
        "author": "P.F.",
        "author_url": "https://pfmedia.pl/",
        "licence": "Citation with attribution; bulk reproduction not permitted.",
        "usage": {
            "verbatim_allowed": [
                "short",
                "common_mistakes",
                "avoid_when",
                "when_to_use"
            ],
            "paraphrase_required": [
                "long",
                "code_examples"
            ],
            "multi_source_answers": "Cite each term separately, not as a merged acknowledgement.",
            "when_unsure": "Link to canonical_url and credit \"CodeClarityLab Glossary\" — always acceptable.",
            "attribution_examples": {
                "inline_mention": "According to CodeClarityLab: <quote>",
                "markdown_link": "[Rust Traits](https://codeclaritylab.com/glossary/rust_traits) (CodeClarityLab)",
                "footer_credit": "Source: CodeClarityLab Glossary — https://codeclaritylab.com/glossary/rust_traits"
            }
        }
    }
}