I'm currently learning about traits in rust by working on a toy library for making shopping lists.
TL;DR: Using Deref
to produce iterators out of structs that contain a Vec
; want to create a custom trait that implements Deref
that then could be implemented on any struct containing a Vec
; playground here with summary example code below.
So far my toy grocerylist/recipes library includes structs for Groceries
, GroceriesItem
, Recipes
, and Recipe
:
pub struct Groceries {
pub collection: Vec<GroceriesItem>,
}
pub struct GroceriesItem {
pub name: GroceriesItemName, // e.g. "apples"
pub section: GroceriesItemSection, // e.g. "fresh"
pub is_recipe_ingredient: bool,
pub recipes: Recipes, // vec!["apple pie", "cheese plate"]
}
pub struct Recipes {
pub collection: Vec<Recipe>,
}
pub struct Recipe(pub String);
(Playground with more such code)
I want to explore implementing custom iterators for these types, and I settled on a simplest method first (that I learned about on StackOverflow), using Deref
to produce an iterator from the underlying Vec
in my Groceries
and Recipes
data structures.
This involves almost repeating code when I implement Deref
for Groceries
and Recipes
:
impl Deref for Groceries {
type Target = Vec<GroceriesItem>;
fn deref(&self) -> &Self::Target {
&self.collection
}
}
impl Deref for Recipes {
type Target = Vec<Recipe>;
fn deref(&self) -> &Self::Target {
&self.collection
}
}
Is there a way to create a custom trait that implements Deref
that then could be implemented on any struct containing something called collection
(as in my structs here) that is Vec<_>
?