How it works...

If you've read Chapter 5, Advanced Data Structures; Boxing data, this recipe doesn't need much explanation. By returning an impl trait, we tell the caller of a function to not care about the specific struct that is returned, and that its only guarantee about it is that it implements some trait. In this sense, abstract return types work like the trait objects discussed in the said recipe, with the added bonus of being way faster, as they don't have any overhead. This is useful for returning iterators [37] and closures [43], which we adapted from the recipe about boxes, but also to hide implementation details. Consider our function create_animal[32]. A caller will only care that it returns a struct that implements Animal, but not which exact animal. If a Dog [7] doesn't prove to be the right thing because of changing requirements, you can create a Cat, and return that one without touching the rest of the code, as it all just depends on Animal. This is a form of dependency inversion (https://en.wikipedia.org/wiki/Dependency_inversion_principle).

The conservative in conservative_impl_trait [1] tells us that this is just a part of a bigger feature. At the moment, you can only use it in return types of functions. In the future, you'll be able to use it in traits, constraints, and bindings as well.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
52.15.65.65