How to Use the Extension Trait Pattern

Define a trait and implement it for an external type to add new methods without modifying the original source code.

Use the extension trait pattern by defining a trait for a type you don't own and implementing it for that type within your own module to add new methods without modifying the original definition.

trait MyExtension {
    fn my_new_method(&self) -> String;
}

impl MyExtension for String {
    fn my_new_method(&self) -> String {
        format!("Extended: {}", self)
    }
}

fn main() {
    let s = String::from("hello");
    println!("{}", s.my_new_method());
}