1. 56
    Rustlings traits1: Extending a type with additional functionality by implementing traits
    42s

Rustlings traits1: Extending a type with additional functionality by implementing traits

Chris Biscardi
InstructorChris Biscardi
Share this video with your friends

Social Share Links

Send Tweet

Chris Biscardi: [0:00] Traits in Rust are how we define behavior that can be shared across types. In this case, we have an AppendBar type that declares a function append_bar, and we can implement this trait for any type.

[0:11] In this case, our task is to implement AppendBar for the type String. We're going to use the same function signature as in the trait. Since we're implementing for type String, self as a string, we can also use push_str to push a string slice into self. We'll need to return self at the end because push_str doesn't return self.

[0:29] Note that because we haven't borrowed as mutable, we can't use push_str yet. We have to declare ourselves as mutable so that we can push Bar on. That's how you would implement a trait which defines the function of shared behavior for specific concrete type.