Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does the fold method give the actual element instead of a reference?

Tags:

rust

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?

like image 354
michas Avatar asked Feb 28 '15 11:02

michas


1 Answers

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).

like image 155
Ms2ger Avatar answered Oct 11 '22 04:10

Ms2ger