【问题标题】:Rust lifetimes, data flows into other referencesRust 生命周期,数据流入其他引用
【发布时间】:2019-05-03 08:34:43
【问题描述】:

我编写了以下代码来过滤数据流,这些代码运行良好,直到我从解析简单数字更改为也具有绑定到生命周期的类型,例如 &str&[u8]

use wirefilter::{ExecutionContext, Filter, Scheme};

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

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

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

    fn filter_matches<'s>(&self, filter: &Filter<'s>) -> bool {
        let mut ctx = ExecutionContext::new(Self::scheme());
        ctx.set_field_value("port", self.port).unwrap();
        ctx.set_field_value("name", self.name.as_str()).unwrap();

        filter.execute(&ctx).unwrap()
    }
}

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

    for my_struct in data
        .filter(|my_struct| my_struct.filter_matches(&filter))
        .take(2)
    {
        println!("{:?}", my_struct);
    }

    Ok(())
}

fn expensive_data_iterator() -> impl Iterator<Item = MyStruct> {
    (0..).map(|port| MyStruct {
        port,
        name: format!("http {}", port % 2),
    })
}

如果我尝试编译它,编译器将失败:

error[E0623]: lifetime mismatch
  --> src/main.rs:26:16
   |
21 |     fn filter_matches<'s>(&self, filter: &Filter<'s>) -> bool {
   |                           -----           ----------
   |                           |
   |                           these two types are declared with different lifetimes...
...
26 |         filter.execute(&ctx).unwrap()
   |                ^^^^^^^ ...but data from `self` flows into `filter` here

error: aborting due to previous error

error: Could not compile `wirefilter_playground`.

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

Process finished with exit code 101

我的第一个想法是 self 和 filter 在 fn filter_matches&lt;'s&gt;(&amp;self, filter: &amp;Filter&lt;'s&gt;) -&gt; bool 中应该具有相同的生命周期,但是如果我将签名更改为 fn filter_matches&lt;'s&gt;(&amp;'s self, filter: &amp;Filter&lt;'s&gt;) -&gt; bool 我将开始收到此错误:

error: borrowed data cannot be stored outside of its closure
  --> src/main.rs:38:29
   |
33 |     let filter = scheme
   |         ------ ...so that variable is valid at time of its declaration
...
38 |         .filter(|my_struct| my_struct.filter_matches(&filter))
   |                 ----------- ^^^^^^^^^ -------------- cannot infer an appropriate lifetime...
   |                 |           |
   |                 |           cannot be stored outside of its closure
   |                 borrowed data cannot outlive this closure

error: aborting due to previous error

error: Could not compile `wirefilter_playground`.

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

Process finished with exit code 101

我无法理解原因,Filter&lt;'s&gt; 绑定到 SCHEME,这是延迟生成的,并且绑定到 'static,不允许 filter.execute 引用 &amp;self.name.as_str() 是有道理的,因为它会但是,filter.execute(&amp;ctx) 的签名是 pub fn execute(&amp;self, ctx: &amp;ExecutionContext&lt;'s&gt;) -&gt; Result&lt;bool, SchemeMismatchError&gt; 是否应该在完成后立即删除引用,因为它没有其他生命周期?

为了尝试编译上面的代码,你可以使用Cargo.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"

PS:这可以通过编译 as inside filter_matches 方法来解决,但这有点糟糕,因为用户在尝试过滤时只会收到解析错误,并且可能会更慢。

【问题讨论】:

    标签: rust rust-crates


    【解决方案1】:

    我看到了解决这个问题的两种方法:
    1) 延长self.name 的寿命。这可以通过将expensive_data_iterator 收集到 Vec 中来实现。

    --- let data = expensive_data_iterator();
    +++ let data: Vec<_> = expensive_data_iterator().collect();
    

    2) 减少filter 的生命周期。

    --- let filter = scheme.parse("...")?.compile();
    +++ let filter = scheme.parse("...")?;
    
    --- .filter(|my_struct| my_struct.filter_matches(&filter))
    +++ .filter(|my_struct| my_struct.filter_matches(&filter.clone().compile()))
    

    我省略了其他一些小改动。是的,filter_matches&lt;'s&gt;(&amp;'s self, ...) 在任何一种情况下都是强制性的。

    PS 是的,第二个选项有效,因为 my_structfilter 寿命长。好吧,如果这两种方法都有些糟糕,那么您可以将它们结合起来!按块处理data,将每一个收集到向量中。

    const N: usize = 10; // or any other size
    loop {
        let cur_chunk: Vec<_> = data.by_ref().take(N).collect();
        if cur_chunk.is_empty() {
            break;
        }
        let cur_filter = filter.clone().compile();
        // etc
    }
    

    它只使用 O(N) 内存并且编译过滤器的次数减少了 N 次

    【讨论】:

    • 感谢您的建议!第一个我不能使用,因为该迭代器可能很大和/或无限。我试图避免的第二个是因为我认为编译方法会是一个缓慢的过程,不是吗?另外,第二个选项有效,因为克隆的FilterAst&lt;'s&gt; 及其Filter&lt;'s&gt; 只存在于那个小范围内?
    • @JaysonReis 是的,你是对的过滤器。检查我的编辑
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-07-03
    • 2017-05-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多