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

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.