如何将min_by_key或max_by_key与对迭代期间创建的值的引用一起使用

  • 本文关键字:key by 创建 引用 一起 min max 迭代 rust
  • 更新时间 :
  • 英文 :


我有一个迭代器,它映射一些值,在此过程中创建元组。我需要通过元组上的元素之一获得最大值(这不是Copy(,但内部引用阻碍了(正如稳定时所预期的那样(。

我怎样才能让这样的东西工作?

// Not a Copy type!
#[derive(Ord, PartialOrd, Eq, PartialEq)]
struct t(i8);
fn main() {
    // This works
    let v = vec![(t(0),), (t(1),)];
    v.iter().min_by_key(|v| &v.0);
    // This doesn't
    let v = vec![0, 1];
    v.iter().map(|i| (t(*i),)).min_by_key(|v| &v.0);
}

操场

error[E0495]: cannot infer an appropriate lifetime for borrow expression due to conflicting requirements
  --> src/main.rs:12:47
   |
12 |     v.iter().map(|i| (t(*i),)).min_by_key(|v| &v.0);
   |                                               ^^^^
   |
note: first, the lifetime cannot outlive the anonymous lifetime #2 defined on the body at 12:43...
  --> src/main.rs:12:43
   |
12 |     v.iter().map(|i| (t(*i),)).min_by_key(|v| &v.0);
   |                                           ^^^^^^^^
note: ...so that reference does not outlive borrowed content
  --> src/main.rs:12:47
   |
12 |     v.iter().map(|i| (t(*i),)).min_by_key(|v| &v.0);
   |                                               ^^^^
note: but, the lifetime must be valid for the method call at 12:5...
  --> src/main.rs:12:5
   |
12 |     v.iter().map(|i| (t(*i),)).min_by_key(|v| &v.0);
   |     ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
note: ...so that a type/lifetime parameter is in scope here
  --> src/main.rs:12:5
   |
12 |     v.iter().map(|i| (t(*i),)).min_by_key(|v| &v.0);
   |     ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

他们不能。当值流经迭代器适配器时,它们会被移动。移动值会导致对其的任何引用失效。您正在尝试引用仅存在于迭代器管道中的值;引用的生存时间不够长。这等效于此基本示例:

(0..9).map(|x| &x)

您将需要使用Iterator::min_by

v.iter().map(|i| (X(*i),)).min_by(|a, b| a.0.cmp(&b.0));

这是有效的,因为闭包返回的值是一个没有引用原始值的Ordering

最新更新