Course lesson
Rustlings traits2: Implementing a Trait for a Vector of Strings
- Duration
- 1 min
- Access
- Free
- Transcript
- Available
Course lesson
Chris Biscardi: 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.
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.
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.
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.
Course lesson