Any (not empty) method for Vec

I saw there was big thread already about not_empty method for Vec, but I personally think not having this method is a downside - user have to perform two operations instead of one, when writing code with !is_empty(). In, for example C#, there is Any() method and it is very convenient. Not sure how Any() fits from english language semantics perspective, but at least google tells me it is possible to use it here.

Previous discussion: The is_not_empty() method as more clearly alternative for !is_empty()

1 Like

I was going to say that !vec.is_empty() doesn't perform two operations because is_empty should be #[inline] but, it isn't, and that's odd because len is #[inline]

1 Like

Shouldn't the compiler still be able to inline it, since it is declared inside a generic impl?

1 Like

Wrt. naming, Iterator::any already exists, evaluating a predicate for each element until a true is found or the iterator is exhausted. It looks like Any in C# is used the same way, but has an overload to be called without a predicate with the meaning that any element merely existing is sufficient.

With that, one way to write !v.is_empty() in Rust is v.iter().any(|_| true).

Do you have any concrete examples where you would be asking if a Vec is empty or not? I'm sure sometimes that's exactly what you need because of some contextual meaning, but if you're doing that before possibly extracting an element or similar, code that instead branches on the success of such an operation may be an alternative. Something like these two:

// increment the last element, if any
if let [.., x] = &mut v[..] {
    *x += 1;

// pop and process elements until empty
while let Some(node) = v.pop() {

I was talking about user doing two operations with his hands when writing code (I mean i THOUGHT compiler will optimize it anyway), so thank you for information - if it doesn't.

Well, for me there are pretty commons situations to do something when Vec is not empty - for example existing checks for records in a database or anywhere else, when you need just the fact it DOES exist, and not care about WHAT it is exactly inside.

It is probably extension method there. I personally think "Any" sounds a bit strange for this in C#, but it is super convenient in this situation.

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.