Why is && used in closure arguments?

I have two questions regarding this example :

let a = [1, 2, 3];

assert_eq!(a.iter().find(|&&x| x == 2), Some(&2));
assert_eq!(a.iter().find(|&&x| x == 5), None);
  1. Why is it &&xused in closure arguments and not just x? I understand that it &passes a reference to an object, but what does it mean to use it twice?

    I do not understand what the documentation says:

    Since it find()takes a link, and many iterators iterate over links, this can lead to a confusing situation where the argument is a double link. You can see this effect in the examples below with &&x.

  2. Why Some(&2)are used, and not Some(2)?

+6
source share
2

a [i32; 3]; i32 s. [i32; 3] iter, &[i32]. &[i32] iter, . Iterator<Item=&i32>.

&i32, i32, , . , , , .

find - , Iterator s. , . : , find. , ( ) . , find , .

, , Iterator<Item=T>, Iterator::find , &T a bool. [i32]::iter , Iterator<Item=&i32>. , Iterator::find, , , &&i32. , .

, a.iter().find(|x| ..), x &&i32. i32 2. . x: a.iter().find(|x| **x == 2). - : a.iter().find(|&&x| x == 2). , , . [1]

Some(&2): a.iter() &i32, i32. Iterator::find, , Iterator<Item=T> Option<T>. , Option<&i32>, .


[1]: , Copy. , |&&x| .. &&String, String - , . , |x| **x .. , , .

+8

1) , , , .cloned() . .iter() , , find .

2) .iter() ; .

.cloned(), , , :

assert_eq!(a.iter().cloned().find(|&x| x == 2), Some(2));
+2

Source: https://habr.com/ru/post/1676581/


All Articles