rhoward
rhoward

Reputation: 191

References to references usage

In the accepted answer in this post Why is "&&" being used in closure arguments?, the author of the answer states:

find is a method defined for all Iterators. It lets you look at each element and return the one that matches the predicate. Problem: if the iterator produces non-copyable values, then passing the value into the predicate would make it impossible to return it from find. The value cannot be re-generated, since iterators are not (in general) rewindable or restartable. Thus, find has to pass the element to the predicate by-reference rather than by-value.

  1. If iterators work on references, how can they return a non-copyable type if they only have access to values of reference type?

  2. What is the use of references to references? Some example would be helpful. I'm still new to Rust.

Upvotes: 0

Views: 437

Answers (1)

Caesar
Caesar

Reputation: 8484

  1. Iterators don't work on references. They work on any T, which could be a reference, or some non-copyable owned struct. The find function gets a reference of T. So if T = &i32, find will work with &&i32.
  2. There's nothing very useful about a &&T. But while I personally never needed it, &mut &T can do some interesting things. Consider e.g.:
fn main() {
    let mut foo = "asdf";
    bend(&mut foo);
    println!("{}", foo);
}

fn bend(s: &mut &str) {
    *s = "bsdf";
}

Upvotes: 1

Related Questions