DEV Community

Discussion on: Share a code snippet in any programming language and describe what's going on

Collapse
 
maowtm profile image
maowtm

In Rust you can add functions to other types with traits. This actually adds the like_a_cow function for all types that are printable, including strings. You have to use the trait though.

pub trait LikeACow {
    fn like_a_cow(&self) -> String;
}

impl<T: std::fmt::Display> LikeACow for T {
    fn like_a_cow(&self) -> String {
        format!("Moo {} mooooo", &self)
    }
}

fn main() {
    // need to `use LikeACow;` if used in other modules, but not here.
    let s = "hello";
    println!("{}", s.like_a_cow());
}
Enter fullscreen mode Exit fullscreen mode