trait-concept

Rust Local trait on a foreign type

A trait defined in your crate can be implemented for a type from another crate, including standard-library types. This lets you add a focused capability without modifying the foreign type. Expected output (not executed): true false Why: The trait is local and its implementation is non-overlapping. Common mistake: Thinking the method becomes an inherent method of u32.

Formal Syntax & Structure

rust syntaxrust
impl LocalTrait for ForeignType { /* items */ }

Working Example

Example Snippetrust
trait IsSmall { fn is_small(&self) -> bool; }impl IsSmall for u32 { fn is_small(&self) -> bool { *self < 10 } }fn main() { println!("{} {}", 3_u32.is_small(), 14_u32.is_small()); }
Rust Reference