【发布时间】:2018-10-04 11:08:16
【问题描述】:
我正在学习 Rust,并且对所有权、借用和引用的概念相当了解。我已经读到 Rust Book 第二版的第 8 章。
我正在使用map as given in an exercise 实现mode 函数。我使用Iterator::max_by_key 编写了以下实现:
use std::collections::HashMap;
fn main() {
let vs = vec![0, 0, 1, 1, 3, 4, 5, 6, 3, 3, 3];
let mut counts = HashMap::new();
for num in vs {
let count = counts.entry(num).or_insert(0);
*count += 1;
}
// This works
let u = counts.iter().max_by_key(|v| v.1);
// This doesn't work
let v = counts.iter().max_by_key(|(k, v)| v);
}
我得到以下编译器错误
error[E0495]: cannot infer an appropriate lifetime for pattern due to conflicting requirements
--> src/main.rs:16:43
|
16 | let v = counts.iter().max_by_key(|(k, v)| v);
| ^
|
note: first, the lifetime cannot outlive the anonymous lifetime #2 defined on the body at 16:38...
--> src/main.rs:16:38
|
16 | let v = counts.iter().max_by_key(|(k, v)| v);
| ^^^^^^^^^^
note: ...so that reference does not outlive borrowed content
--> src/main.rs:16:43
|
16 | let v = counts.iter().max_by_key(|(k, v)| v);
| ^
note: but, the lifetime must be valid for the method call at 16:13...
--> src/main.rs:16:13
|
16 | let v = counts.iter().max_by_key(|(k, v)| v);
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
note: ...so that a type/lifetime parameter is in scope here
--> src/main.rs:16:13
|
16 | let v = counts.iter().max_by_key(|(k, v)| v);
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
这个错误是什么意思,为什么这是不允许的?
更新 1: Match tuple as input to map 解决了我的问题。如果我使用的是稳定的编译器,我就不会问这个问题。在这里我遇到了意外的编译错误,所以我不会将其作为重复项关闭。
【问题讨论】:
-
您使用的是夜间编译器,不是吗?如果你切换到稳定版,你可以看到这个问题的实际修复。
-
哇!我使用了稳定的编译器,它给了我一个直接的修复。我怎么知道以后会这样?
-
@ljedrz 我认为我们不应该将其作为重复项关闭,因为这可能是夜间编译器错误的第一个问题(这些符合人体工程学的改进......)。