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
Published 4 years ago
Updated 3 years ago

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.

egghead
egghead
~ 2 hours ago

Member comments are a way for members to communicate, interact, and ask questions about a lesson.

The instructor or someone from the community might respond to your question Here are a few basic guidelines to commenting on egghead.io

Be on-Topic

Comments are for discussing a lesson. If you're having a general issue with the website functionality, please contact us at support@egghead.io.

Avoid meta-discussion

  • This was great!
  • This was horrible!
  • I didn't like this because it didn't match my skill level.
  • +1 It will likely be deleted as spam.

Code Problems?

Should be accompanied by code! Codesandbox or Stackblitz provide a way to share code and discuss it in context

Details and Context

Vague question? Vague answer. Any details and context you can provide will lure more interesting answers!

Markdown supported.
Become a member to join the discussionEnroll Today