Do you need a reference to the second value to sort tuple vectors?

I have a vector of integer tuples and want to sort them by the second element of each tuple:

fn main() {
    let mut tuple_list2: Vec<(u16,u16)> = vec![(1,5),(0,17),(8,2)];
    tuple_list2.sort_by(|a,b| a.1.cmp(b.1));
}

The compiler throws an error because B.1 is a U16 rather than a reference to a (& U16) I can solve this problem by quoting B.1:

fn main() {
    let mut tuple_list2: Vec<(u16,b| a.1.cmp(&b.1));
}

I don't understand why I did it Especially because I don't need to quote a.1

Solution

As aurora0001 has pointed out in his comments, we should look at the function signature of cmp():

fn cmp(&self,other: &Self) -> Ordering

We see that both values are obtained by reference, so you have to pass & B.1 to the method instead of B.1

This is a more interesting question; -)

The simple solution is The (DOT) operator performs automatic dereference and automatic borrowing Let's look at its actual effect:

struct Foo;

impl Foo {
    fn takes_value(self) {}
    fn takes_ref(&self) {}
    fn takes_mut_ref(&mut self) {}
}

fn main() {
    let mut a = Foo;

    // all of those work thanks to auto-borrowing
    a.takes_ref();
    a.takes_mut_ref();
    a.takes_value();

    // --------
    let b = Foo;
    let c = &mut b;

    // these work as well
    c.takes_ref();
    c.takes_mut_ref();

    // this one works,*if* the type implements `Copy`
    c.takes_value();
}

So Operator can help programmers and always pass correct self parameters

Note: the sort you do is very common There is a better method for this task: [t]: sort_ by_ key(). It looks like this:

// note: type annotations not required
let mut tuple_list2 = vec![(1,2)];
tuple_list2.sort_by_key(|k| k.1);
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>