1

我正在编写一个程序来使用wirefilter来过滤来自无限流的数据。

但是由于生命周期,我似乎无法在循环中使用已编译的 ast,当我尝试编译时,这是输出:

error: borrowed data cannot be stored outside of its closure
  --> src/main.rs:34:33
   |
31 |     let filter = ast.compile();
   |         ------ ...so that variable is valid at time of its declaration
32 | 
33 |     for my_struct in data.filter(|my_struct| {
   |                                  ----------- borrowed data cannot outlive this closure
34 |         let execution_context = my_struct.execution_context();
   |                                 ^^^^^^^^^ ----------------- cannot infer an appropriate lifetime...
   |                                 |
   |                                 cannot be stored outside of its closure

error: aborting due to previous error

error: Could not compile `wirefilter_playground`.

To learn more, run the command again with --verbose.

main.rs

use wirefilter::{ExecutionContext, Scheme};

lazy_static::lazy_static! {
    static ref SCHEME: Scheme = Scheme! {
        port: Int
    };
}

#[derive(Debug)]
struct MyStruct {
    port: i32,
}

impl MyStruct {
    fn scheme() -> &'static Scheme {
        &SCHEME
    }

    fn execution_context(&self) -> ExecutionContext {
        let mut ctx = ExecutionContext::new(Self::scheme());
        ctx.set_field_value("port", self.port).unwrap();

        ctx
    }
}

fn main() -> Result<(), failure::Error> {
    let data = expensive_data_iterator();
    let scheme = MyStruct::scheme();
    let ast = scheme.parse("port in {2 5}")?;
    let filter = ast.compile();

    for my_struct in data.filter(|my_struct| {
        let execution_context = my_struct.execution_context();
        filter.execute(&execution_context).unwrap()
    }).take(10) {
        println!("{:?}", my_struct);
    }

    Ok(())
}

fn expensive_data_iterator() -> impl Iterator<Item=MyStruct> {
    (0..).map(|port| MyStruct { port })
}

货运.toml

[package]
name = "wirefilter_playground"
version = "0.1.0"
edition = "2018"

[dependencies]
wirefilter-engine = "0.6.1"
failure = "0.1.5"
lazy_static = "1.3.0"

有可能让它工作吗?我只想为最终用户生成过滤后的数据,否则内存中的数据量会很大。先感谢您!

4

1 回答 1

2

看起来问题在于返回结构中的生命周期省略。特别是这段代码:

fn execution_context(&self) -> ExecutionContext {
    //...
}

相当于这个:

fn execution_context<'s>(&'s self) -> ExecutionContext<'s> {
    //...
}

一旦您意识到它ExecutionContext具有相关的生命周期,这一点就变得显而易见了。

的生命周期ExecutionContext不必与 的生命周期相匹配,MyStruct因此您可能要编写:

fn execution_context<'e>(&self) -> ExecutionContext<'e> {
    //...
}

或许:

fn execution_context<'s, 'e>(&'s self) -> ExecutionContext<'e>
where 'e: 's {
    //...
}

取决于您的上下文是否最终会引用MyStruct.

于 2019-04-29T14:31:04.517 回答