According to the rust book for iterators there are consumers like find
and fold
.
They are used as:
let greater_than_forty_two = (0..100).find(|x| *x > 42);
and
let sum = (1..4).fold(0, |sum, x| sum + x);
In both cases x
is the current value. However in the first case x
is a reference and in the second case it is the element itself.
As far as I understood from the for
loop, it has to be a reference to avoid owner problems. But shouldn't there be the same owner problem in the fold case?
The issue is somewhat hard to explain with integers, since they are Copy
, so compare:
let v = vec!["a".to_string(), "b".to_string()];
let result = v.into_iter().find(|s| s.starts_with("b"));
result == Some("b".to_string())
let v = vec!["a".to_string(), "b".to_string()];
let result = v.into_iter().fold("".to_string(), |a, s| s + &a);
result == "ba".to_string()
In the first case, the String
needs to be returned to the caller, so we can't have the closure destroy it (which would happen if it was passed by value). In the second, the values are no longer used after the call to the closure, so they can be passed to the closure by value (which allows us to consume the String
when we append to it).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With