Deref operator is not working as expected?

   let mut x = vec![1,2,3,4,5,6];
   //   let all = x.iter().all(|val: &i32| val>=1);
   let all = x.iter().all(|&val| val>=1);
   assert_eq!(all, true);

If u see above code, I'm calling an all method in the Iterator trait, and its working fine, but the problem is with the closure inside the all method. If you see the comment line(2nd line), the type of val variable is &i32 and, usually, we can deref with * operator, but in this code (line3)

.all(|&val| val>=1);

they used a reference to dereference the val variable.

that's not dereferencing the variable, that's the pattern to bind the variable. a single identifier is the most common pattern for variable bindings, but bindings to variable is not limited to a simple identifier. in this particular case, it's a reference pattern:

https://doc.rust-lang.org/stable/reference/patterns.html?highlight=binding#reference-patterns

If that were the case then how this below code works, its the same right?

let a = &10; // type of a is &i32
let b = &a;  // type of b is &&i32

But overthere in closure

val:&i32
and when u put a "&" infront of val, it become i32
&val : i32

How is that possible?

notice how the & sign is used in front of the variable c, d, e, f:

let a = &10; // a: &i32
let b = &a; // b: &&i32
let &c = b; // c: &i32
let &d = c; // d: i32
let &e = &10; // e: i32
let &f = &&10; // f: &i32

that's why it's called "pattern matching"

1 Like

Oh..that was a new info..thank u

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.