0

我编写了一个简单的程序来测试 Cloudflare 的wirefilter,这是一个有效的示例。

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) -> Result<ExecutionContext, failure::Error> {
        let mut ctx = ExecutionContext::new(Self::scheme());
        ctx.set_field_value("port", self.port)?;

        Ok(ctx)
    }
}

fn main() -> Result<(), failure::Error> {
    let data: Vec<MyStruct> = (0..10).map(|i| MyStruct { port: i as i32 }).collect();
    let scheme = MyStruct::scheme();
    let ast = scheme.parse("port in {2 5}")?;
    let filter = ast.compile();

    for i in data
        .iter()
        .filter(|d| filter.execute(&d.execution_context().unwrap()).unwrap())
    {
        println!("{:?}", i);
    }

    Ok(())
}

这将打印:

MyStruct { port: 2 }
MyStruct { port: 5 }

data 如果我在验证模式后创建向量,借用系统将开始抱怨。

我想"port in {2 5}"在创建该向量之前验证用户输入,这是一项昂贵的操作,有什么办法吗?

代码的第二个版本是:

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) -> Result<ExecutionContext, failure::Error> {
        let mut ctx = ExecutionContext::new(Self::scheme());
        ctx.set_field_value("port", self.port)?;

        Ok(ctx)
    }
}

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

    let data: Vec<MyStruct> = (0..10).map(|i| MyStruct { port: i as i32 }).collect();
    for i in data.iter().filter(|d| filter.execute(&d.execution_context().unwrap()).unwrap()) {
        println!("{:?}", i);
    }

    Ok(())
}

这将失败并显示此消息:

error[E0597]: `data` does not live long enough
  --> src/main.rs:33:14
   |
33 |     for i in data.iter().filter(|d| filter.execute(&d.execution_context().unwrap()).unwrap()) {
   |              ^^^^ borrowed value does not live long enough
...
38 | }
   | -
   | |
   | `data` dropped here while still borrowed
   | borrow might be used here, when `filter` is dropped and runs the destructor for type `wirefilter::filter::Filter<'_>`
   |
   = note: values in a scope are dropped in the opposite order they are defined

似乎我可以在data创建之前解析查询,但我无法编译它。

4

1 回答 1

1

您可以将声明与其data赋值分开:

let data: Vec<MyStruct>;
let scheme = MyStruct::scheme();
let ast = scheme.parse("port in {2 5}")?;
let filter = ast.compile();
data = (0..10).map(|i| MyStruct { port: i as i32 }).collect();

的生命周期与data代码的第一个版本相同,而分配与第二个版本同时发生。

于 2019-04-28T09:28:18.240 回答