我有一个整数元组向量,想按每个元组的第二个元素对它进行排序:
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));
}
编译器会抛出一个错误,因为 b.1
是一个 u16
而不是对一个 (&u16
) 的引用。我可以通过引用 b.1
来解决这个问题:
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));
}
我不明白为什么我必须这样做。特别是因为我也不需要引用 a.1
。
最佳答案
正如 Aurora0001 已经在评论中指出的那样,我们应该看看 the function signature of cmp()
:
fn cmp(&self, other: &Self) -> Ordering
我们看到这两个值都是通过引用获取的,因此您必须将 &b.1
而不是 b.1
传递给该方法也就不足为奇了>。
Especially because I do not need to reference
a.1
, either.
这是一个更有趣的问题;-)
简单的解决方案是,.
(点)运算符执行自动解引用和自动借用。让我们看看它的实际效果:
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();
}
所以 .
运算符可以帮助程序员并始终传递正确类型的 self
参数。
注意:您进行的排序很常见。有一种方法更适合这项任务:[T]::sort_by_key()
.它看起来像这样:
// note: type annotations not required
let mut tuple_list2 = vec![(1, 5), (0, 17), (8, 2)];
tuple_list2.sort_by_key(|k| k.1);
关于对元组向量进行排序需要第二个值的引用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40091161/