New week, new Rust! What are you folks up to?
I have had quite a long break from Rust and programming ( about a year ), and thought I would do something. I forgot a lot.
My current idea is a kind of cache ( not sure that's the right word ) which could be used to hold old values. Imagine a database where readers get a virtual copy of the database at the time they start reading, which do not block updates to the database.
So I made a Cache struct, with appropriate methods. Playground link
One minor question I have : I have methods like this ( values is a BTreeMap ).
fn first( &self ) -> Time
{
for key in self.values.keys()
{
return *key;
}
Time::MAX
}
Clippy says : "This loop never loops, all it does is obfuscating the code."
It's true it never loops, but I don't see what else I can do. I want to get the first key in values.
Is there some trick that doesn't "obfuscating the code" I can use?
is an Iterator, and any Iterator has a
fn take(self, n: usize) -> Take<Self>
which (as per the docs)
Creates an iterator that yields the first
n
elements, or fewer if the underlying iterator ends sooner.
take(n)
yields elements untiln
elements are yielded or the end of the iterator is reached (whichever happens first). The returned iterator is a prefix of lengthn
if the original iterator contains at leastn
elements, otherwise it contains all of the (fewer thann
) elements of the original iterator.
Therefore, you can simply
if let Some(k) = self.values.take(1) {
return *k;
} // else
return Time::MAX
Thanks! That didn't quite work... I think because take just returns another iterator, which doesn't help.
Using your helpful link to the iterator documentation, this worked, but IMO it's more obscure than the original!
fn first( &self ) -> Time
{
if let Some(key) = self.values.keys().find(|&_x|true)
{
*key
}
else { Time::MAX }
}
You can use Iterator::next()
to get the first item directly:
fn first( &self ) -> Time {
match self.values.keys().next() {
Some(&t) => t,
None => Time::MAX
}
}
Nice! You did a quick edit there, I found this works :
fn first( &self ) -> Time
{
*self.values.keys().next().unwrap_or( &Time::MAX )
}
This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.