简体   繁体   English

Rust 高阶函数的寿命

[英]Rust Lifetimes in Higher Order Functions

I have a map: HashMap<&str, Vec<&str>> and I'm trying to create a reverse lookup map HashMap<&str, &str> which refers from each of the element in the original vector to the original key.我有一个 map: HashMap<&str, Vec<&str>>并且我正在尝试创建一个反向查找 map HashMap<&str, &str> ,它从原始向量中的每个元素指向原始键。

Eg map like below例如 map 如下

{
  "k": vec!["a", "b"]
} 

would be transformed into会变成

{
  "a": "k",
  "b": "k",
} 

It works perfectly fine when I do that with:当我这样做时,它工作得很好:

    let substitutes: HashMap<&str, Vec<&str>> = vec![("a", vec!["b", "c"])].into_iter().collect();
    
    // Below works fine
    let mut reversed: HashMap<&str, &str> = HashMap::new();
    for (&k, v) in substitutes.iter() {
        for vv in v.iter() {
            reversed.insert(vv, k);
        }
    }

However it doesn't work if I try to do that with a Higher Order Functions:但是,如果我尝试使用高阶函数来做到这一点,它就不起作用:

    // Below doesn't work
    let reversed_2: HashMap<&str, &str> = substitutes
        .iter()
        .flat_map(|(&k, v)| v.iter().map(|&vv| (vv, k)))
        .collect();

And gives the following errors:并给出以下错误:

error[E0373]: closure may outlive the current function, but it borrows `k`, which is owned by the current function
  --> src/main.rs:18:42
   |
18 |         .flat_map(|(&k, v)| v.iter().map(|&vv| (vv, k)))
   |                                          ^^^^^      - `k` is borrowed here
   |                                          |
   |                                          may outlive borrowed value `k`
   |
note: closure is returned here
  --> src/main.rs:18:29
   |
18 |         .flat_map(|(&k, v)| v.iter().map(|&vv| (vv, k)))
   |                             ^^^^^^^^^^^^^^^^^^^^^^^^^^^
help: to force the closure to take ownership of `k` (and any other referenced variables), use the `move` keyword
   |
18 |         .flat_map(|(&k, v)| v.iter().map(move |&vv| (vv, k)))
   |                                          ^^^^^^^^^^

error: aborting due to previous error; 1 warning emitted

I am trying to wrap my head around how vv might outlive k given that it's in the same scope under flat_map .鉴于 vv 在 flat_map 下的同一个 scope 中,我正试图围绕vv如何比kflat_map

Would be really helpful to get more information why my HOF approach fails.获得更多关于我的 HOF 方法失败的信息将非常有帮助。

Playground 操场

In this case, the compiler help was exactly right: you need to add move on the inner closure.在这种情况下,编译器的帮助是完全正确的:您需要在内部闭包上添加move

let reversed_2: HashMap<&str, &str> = substitutes
    .iter()
    .flat_map(|(&k, v)| v.iter().map(move |&vv| (vv, k)))
    .collect();

Rust Playgroud Rust 游乐场

When you make an anonymous function that uses variables from the surrounding scope, the inline function (called a closure ) needs access to those variables.当您使用来自周围 scope 的变量创建匿名 function 时,内联 function(称为闭包)需要访问这些变量。 By default, it takes a reference to them, leaving them available in the enclosing scope.默认情况下,它引用它们,使它们在封闭的 scope 中可用。 However, in this case, the closure takes a reference to k and returns it, which means that it could escape the enclosing scope.但是,在这种情况下,闭包会引用k并返回它,这意味着它可以逃脱封闭的 scope。

.flat_map(|(&k, v)| {
    // k is only valid in this anonymous function

    // a reference to k is returned out of map and also out of flat_map
    // (Note: no move)
    v.iter().map(|&vv| (vv, k))

    // the anonymous function ends, all references to k need to have ended
})

// A reference to k has been returned, even though k's lifetime has ended
// Compiler error!

When you switch to a move closure, rather than taking to references to things in the enclosing environment, you take ownership of the things themselves.当您切换到move闭包时,您无需引用封闭环境中的事物,而是获得事物本身的所有权。 This lets you return k rather than a reference to k , sidestepping the issue.这使您可以返回k而不是对k的引用,从而回避了这个问题。

.flat_map(|(&k, v)| {
    // k is only valid in this anonymous function

    // k is moved out of the enclosing function and into the inner function
    // Because it owns k, it can return it
    // (Note: uses move)
    v.iter().map(move |&vv| (vv, k))

    // k has been moved out of this environment, so its lifetime does not end here
})

// k has been returned and is still alive

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM