Through this, we can do things like write a single function that accepts multiple types. In this case, that behavior is actually all we care about, so we can leverage polymorphism to be more flexible, but maintain a set of required functionality. In this example, we can accept any concrete type as long as they implement a growl() method. Instead, polymorphism allows us to create functions that accept any type, as long as those types exhibit certain behaviors or properties that we need them to have. This results in a lot of unnecessarily duplicate code, which becomes difficult to maintain. If we wanted to have similar functionality, but for other types, we’d have to create additional functions to accept those types. If you design an API around specific, concrete types, then you’re committed to that approach, and so are your consumers.Īs an example - if we wrote a function that requires a type - Lion as a parameter, we’re bound to that decision strictly. There are several practical advantages to using polymorphism, but one of the biggest is code re-use. This allows us to create more flexible APIs which give more control to the consumer and are easier to maintain. In my own words, polymorphism gives us the ability to present a single interface for potentially many different concrete types. If you’re reading this post, you’ve almost certainly heard of the term “polymorphism”. ![]() In this post, I’d like to take a step back and look at the full spectrum of options Rust makes available for accomplishing polymorphism, and get under the covers so we fully understand the tradeoffs of the decisions we make as Rust developers. In the previous post we explored the use of generic types in Rust and some of the common reasons for doing so.
0 Comments
Leave a Reply. |
AuthorWrite something about yourself. No need to be fancy, just an overview. ArchivesCategories |