The value of `&&a`

I'm doing the exercise, rustingls iterators5

fn count_iterator(map: &HashMap<String, Progress>, value: Progress) -> usize {
    // map is a hashmap with String keys and Progress values.
    // map = { "variables1": Complete, "from_str": None, ... }
    //todo!();
    //   &Progress   &&Progress
    map.values().filter(|x| x == &&value).count()
}

values() returns an iterator of which the element type is &'a V.
filter will take a predicate function as parameter which type is &Self::item, that it is also a reference.

So the type of x of |x| is &&Progress

The code passes the tests.

But my doubt is what's the value of &&Progress and what's the difference between **x==value and x==&&value


I did following test:

rust playground

fn main(){
    let a = 1;
    println!("{:p}",&a);
    println!("{:p}",&&a);
    println!("{:p}",&&a);
}
/*
0x7ffe58e66c0c
0x7ffe58e66ca0
0x7ffe58e66cf0   //not same as previous
*/

Printing &a is actually getting the address that memory storing the value 1

But &&a ? Since I didn't do such thing like b =&a, that we did allocate a memory space for storing &a , it's value seems unpredictable , otherwise it make more sense that getting &b is just getting another address like &a.

There is no difference between **x == value and x == &&value. The == operator does not compare addresses when you give it a reference. Instead, it just compares the underlying value.

9 Likes

OH! Thx!

In functionality? No difference at all.

In technical details? The latter ends up using the impl<A, B> PartialEq<&B> for &A where A: PartialEq<B> implementation twice to dereference twice and call the same thing that the first one would call.

So use whichever one you like the look of better.

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.