1. 57
    Rustlings traits2: Implementing a Trait for a Vector of Strings
    1m 1s

Rustlings traits2: Implementing a Trait for a Vector of Strings

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] In traits1, we said that we can implement a trait for any type. In traits2, our task is to implement the trait 'AppendBar' for a vector of strings. If we look at tests, we can see that a vector with one value "Foo" that has bar appended to it results in "Bar" and then "Foo" being popped off the stack.

[0:19] If we look at our test, we can see that we have a mut foo as a vector that starts out as just a vector of foo and then receives a bar. If we pop an element off of foo and unwrap it, we get the string bar. If we pop the remaining element off and unwrap it, we get a string foo.

[0:34] The implementation for AppendBar is going to push bar into the vector. We'll specify that we're implementing AppendBar for a Vec<String>. We'll use the same function signature as specified in the trait.

[0:47] Now, we have an impl AppendBar for a Vec<String>. We have the function append_bar() where Self is a vector of strings, and we can push a String onto that vector and return the vector. Note that we also have a mut self. This passes our tests.

egghead
egghead
~ an hour 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