创建依赖项成本很高时该怎么办?

时间:2019-04-28 09:16:50

标签: rust rust-crates

我编写了一个简单的程序来测试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之前解析查询,但是无法编译它。

1 个答案:

答案 0 :(得分: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的生存期与代码的第一个版本相同,而赋值与第二个版本同时进行。