.any(|_| true)
.any(...)
returns true
.any(|_| true)
will always return true
.any(...)
returns false
.count()
?
.next().is_some()
, maybe?
.any(...)
needs predicate in case you're using it in uncommon way? :)
false
if empty
any
answers the question "is there an element for which ... keeps". If there are no elements, the answer is obvious :-)
.len()
if you have an ExactSizeIterator
.peekable()
you'll get an iterator from which you can peek in and see whether it has a next element
Iterator::any
requires a predicate, it has to take one argument.
is_empty
method on the Peekable
wrapper.
.any()
will actually cause the iterator to compute all remaining elements
.any(predicate)
. Since Rust doesn't have overloading like that I often omit arguments when talking about the functions themselves.
impl
's ExactSizeIterator
, it will have an is_empty
. Although it's not stable, so you'd have to use nightly and #![feature(exact_size_is_empty)]
.
.any(pred)
is going to really surprise you with what it does
ExactSizeIterator
has the len
function, so you could do it.len() == 0
, which is probably going to be the exact same machine code in virtually all cases.
.any(|_| true)
will chop off an element of your iterator if it finds one
Peekable
is what you want
.next().is_some()
will do the same as .any(|_| true)
.peekable()
to the code that generates your iterator
.peek().is_some()
ExactSizeIterator
s
.peekable()
consumes an iterator and produces a wrapper Peekable<OldIterator>
Peekable
will let you do it pretty much for free
let a = [1, 2, 3];
assert!(a.iter().any(|&x| x > 0));
assert!(!a.iter().any(|&x| x > 5));
.is_empty()
Vec
, also .is_empty()
.is_empty()
Iterator
trait bound - then Peekable
, I think, is your best option
slice.iter().any(|_| true)
over slice.is_empty()
? :P
.is_empty()
or whatever is available rather than sticking to what you're used to. It's an idiom from a different language after all.
std::collections
- each one has is_empty()
slice.iter().any(|_| true)
and slice.is_empty()
compiles into same bytecode
pub fn reply(phrase: &str) -> &str {
if phrase.chars().last() == Some('?') {
"Sure."
} else if phrase.chars().any(|c| c.is_uppercase())
&& !phrase.chars().any(|c| c.is_lowercase()) {
"Whoa, chill out!"
} else if !phrase.chars().any(|_| true) {
"Fine. Be that way!"
} else {
"Whatever."
}
}
this is not idiomatic right? any advice?
.all(|c|c.us_uppercase())
maybe
&static str
?
&'static str
String
.
&str
, &'static str
works
&'static str
when all your paths return literals / constants.