Today I had a bit of fun learning how to get more into the head-space on defining better parameters in my rust functions when they work with a collection. Let’s go on a journey and get to the final evolution of where I ended up and what was learned.
First we’ll need to start with a small snippet of code to get an idea of where
it started. In this case I was tinkering with a simple cache store of a
HashMap where the values are insulated in an
I then wanted to add a bulk fetch method which would utilize a single read lock to bulk fetch as many cached items via keys. My first pass ended up looking like this:
Sweet, tests pass and we are in business! Now lets plug it in roughly to the code path I was hoping to use it in…
It turns out a slice won’t work, so it’s back to the drawling board. I’m not
actually even using the slice directly really, I’m just using the iterator it
.iter(). So why not just require an iterator to begin with? Here
is what my next try looked like.
This works now for any iterator; however, I’m not a fan of the
that is needed now to get it to work for different collections that can produce
an iterator. It turns out that there is also a trait that covers this as well,
and it’s called
This lets you use a reference to any collection which implements
I’m pretty happy with what was learned while tinkering with this caching idea.
Can’t say if the whole thing in total is worth anything, but this little bit of
insight gained is a big one. When first starting with rust it felt like I was
wanting to work with slices; however, more often then not what’s being called
for is an iterator. If you find yourself in the same spot then hopefully this
has opened your eyes!