1. 60
    Rustlings generics3: Constraining generics using traits
    1m 32s

Rustlings generics3: Constraining generics using traits

Chris Biscardi
InstructorChris Biscardi
Share this video with your friends

Social Share Links

Send Tweet

README for this exercise.

Chris Biscardi: [0:00] In generics3, we have a struct ReportCard that we need to change one of the field on to be able to accept the generic type. In this case, it needs to accept f32 as well as strings. For this, we'll specify a generic type T with the grade type.

[0:13] Note that if we just put it on the grade type, T can't be found in scope because T isn't anything. It doesn't identify anything. T is not special. It's just a character that we chose to use. We also need to say that the thing that we're referring to is a type.

[0:27] Now that we've specified our struct type -- this parameterized over type T and that we use type T as the grade -- we can take a look at the implementation, which expects the type argument now and doesn't currently use one. If we just put the T on the right hand side of the ReportCard, we could see that it's not found in scope.

[0:41] We need it after the implementation as well. Now with the generic type in place, the program is trying to use the generic type and trying to use the ReportCard specifically, but T cannot be formatted with the default formatter. That is, it can't be put into a format macro like we are right here.

[0:56] To fix this, we're going to say that T has the Display trait. The Display trait is implemented for any type that can be used in format. Note that now that we've set our generic type T, pass the implement the display trait, our tests are mostly working.

[1:10] If we go down to the tests, we can see that one of them is actually wrong. In this case, we're trying to assert_eq! That report_card.print achieves a grade of A+, but we're not passing in A+ here.

[1:20] Let's do that. Now, we can see that the grade that we used in the first test, 2.1, and the grade that we used in the second test, A+, both work. That's how we use generics to constrain them to a specific trait and work across multiple types.