How to Use Extension Traits in Rust

Extension traits allow adding methods to external types by defining and implementing a trait for them.

Extension traits let you add methods to types you don't own by defining a trait and implementing it for that type. You define the trait with the desired methods, then implement it for the external type, allowing you to call those methods as if they were native.

trait MyExtension {
    fn my_method(&self);
}

impl MyExtension for String {
    fn my_method(&self) {
        println!("Extended: {}", self);
    }
}

fn main() {
    let s = String::from("Hello");
    s.my_method();
}