Double Double
Explore the concept of traits in Rust to manage shared behavior across different types. Understand how to define traits, implement them for multiple types, and use methods to write reusable, flexible code while handling compiler constraints.
We'll cover the following...
Traits show up so much in Rust that we’ve already mentioned them multiple times in our previous lessons. It’s time to finally dive into this topic. We’ll start off with some simpler examples of traits. Then, we’ll get into some stronger motivation for using traits, focusing on some limitations we cleverly avoided with type parameters previously.
Let’s say I want to write a function that can double both i32s and i64s. I’m going to start off by using the ugly “add the type to the name” approach and end up with two functions:
But I don’t like that at all! This feels like something that would be much more pleasant if:
-
I had the same name for both types
-
I could use method syntax
So, let’s go ahead and try to write two impl blocks:
Unfortunately, this doesn’t work. And perhaps more unfortunately, ...