使用闭包返回对枚举变量内容的引用时,“无法推断适当的生存期”

时间:2019-02-13 19:09:23

标签: enums reference rust lifetime

我有一个函数可以接受对枚举的引用,我需要通过匹配枚举并读取其内容来进行解析。枚举的一种变体(不在下面的简化的最小工作示例中),可能包含枚举本身的类型作为值,因此我可能需要递归调用同一函数来解析其值。

我想编写一个充当过滤器的函数,并返回一个包含对enum变量内容的引用的Option::Some;如果必须舍弃该值,则返回None

下面是一个最小的工作(非真正编译)示例:

enum Data<'a> {
    Value(&'a String),
    Null,
}

fn main() {
    let s = String::new();
    let d = Data::Value(&s);

    let equal = |d: &Data| -> Option<&String> {
        if let Data::Value(s) = d {
            Some(s)
        } else {
            None
        }
    };

    parse(&d, equal);
    //parse(&d, equal_filter);
}

fn equal_filter<'a>(d: &'a Data) -> Option<&'a String> {
    if let Data::Value(s) = d {
        Some(s)
    } else {
        None
    }
}

fn parse<'a, F>(data: &Data<'a>, filter: F)
where
    F: Fn(&Data<'a>) -> Option<&'a String>,
{
    filter(data);
}

Playground

我尝试先使用闭包来编译代码,但在这种情况下,我得到了错误:

error[E0495]: cannot infer an appropriate lifetime due to conflicting requirements
  --> src/main.rs:11:33
   |
11 |         if let Data::Value(s) = d {
   |                                 ^
   |
note: first, the lifetime cannot outlive the anonymous lifetime #2 defined on the body at 10:17...
  --> src/main.rs:10:17
   |
10 |       let equal = |d: &Data| -> Option<&String> {
   |  _________________^
11 | |         if let Data::Value(s) = d {
12 | |             Some(s)
13 | |         } else {
14 | |             None
15 | |         }
16 | |     };
   | |_____^
   = note: ...so that the types are compatible:
           expected &Data<'_>
              found &Data<'_>
note: but, the lifetime must be valid for the expression at 18:5...
  --> src/main.rs:18:5
   |
18 |     parse(&d, equal);
   |     ^^^^^
note: ...so that a type/lifetime parameter is in scope here
  --> src/main.rs:18:5
   |
18 |     parse(&d, equal);
   |     ^^^^^

所以我尝试了一个函数,但是又遇到另一个错误:

error[E0271]: type mismatch resolving `for<'r> <for<'a, 's> fn(&'a Data<'s>) -> std::option::Option<&'a std::string::String> {equal_filter} as std::ops::FnOnce<(&'r Data<'_>,)>>::Output == std::option::Option<&std::string::String>`
  --> src/main.rs:19:5
   |
19 |     parse(&d, equal_filter);
   |     ^^^^^ expected bound lifetime parameter, found concrete lifetime
   |
note: required by `parse`
  --> src/main.rs:30:1
   |
30 | / fn parse<'a, F>(data: &Data<'a>, filter: F)
31 | | where
32 | |     F: Fn(&Data<'a>) -> Option<&'a String>,
33 | | {
34 | |     filter(data);
35 | | }
   | |_^

我更愿意使用闭包来解决问题,但即使使用该功能,我也不知道如何继续。

1 个答案:

答案 0 :(得分:2)

最终,这是由于limitations in Rust's type inference引起的。具体来说,如果将闭包立即传递给使用它的函数,则编译器可以推断出参数和返回类型是什么。不幸的是,当在使用它之前将其存储在变量中时,编译器不会执行相同级别的推断。

内联闭包,它可以工作:

enum Data<'a> {
    Value(&'a String),
    Null,
}

fn main() {
    let s = String::new();
    let d = Data::Value(&s);

    parse(&d, |d| match d {
        Data::Value(s) => Some(s),
        _ => None,
    });
}

fn parse<'a, F>(data: &Data<'a>, filter: F)
where
    F: Fn(&Data<'a>) -> Option<&'a String>,
{
    filter(data);
}

但是,我建议您改为在枚举上创建方法并加入idiomatic set of conversion functions

enum Data<'a> {
    Value(&'a String),
    Null,
}

impl<'a> Data<'a> {
    fn as_value(&self) -> Option<&'a str> {
        match self {
            Data::Value(s) => Some(s),
            _ => None,
        }
    }
}

fn main() {
    let s = String::new();
    let d = Data::Value(&s);

    parse(&d, Data::as_value);
}

fn parse<'a, F>(data: &Data<'a>, filter: F)
where
    F: Fn(&Data<'a>) -> Option<&'a str>,
{
    filter(data);
}

您的函数变体不起作用,因为您将相关生命周期放置在错误的位置:

// Wrong
fn equal_filter<'a>(d: &'a Data) -> Option<&'a String>
// Right
fn equal_filter<'a>(d: &Data<'a>) -> Option<&'a String>

使用#[deny(elided_lifetimes_in_paths)]#[deny(rust_2018_idioms)]可以指导您:

error: hidden lifetime parameters in types are deprecated
  --> src/main.rs:12:22
   |
12 |     let equal = |d: &Data| -> Option<&String> {
   |                      ^^^^- help: indicate the anonymous lifetime: `<'_>`
   |
error: hidden lifetime parameters in types are deprecated
  --> src/main.rs:24:28
   |
24 | fn equal_filter<'a>(d: &'a Data) -> Option<&'a String> {
   |                            ^^^^- help: indicate the anonymous lifetime: `<'_>`

另请参阅: