类型注释需要静态生命周期

问题描述 投票:0回答:1

我想使用这个板条箱计算函数的积分:https://docs.rs/reikna/latest/reikna/integral/fn.integrate.html

当我想动态生成我想要集成的函数时,出了问题。

use reikna::integral::*;
use reikna::func;

fn calc(i: f64) -> f64 {
    let f = func!(|x| i + x);
    return integrate(&f, 0.0, 100.0);
}


fn main() {
    let res = calc(50.0);
    println!("The result is: {}", res);
}

我收到此错误:

error[E0597]: `i` does not live long enough
 --> src/main.rs:5:23
  |
5 |     let f = func!(|x| i + x);
  |             ----------^-----
  |             |     |   |
  |             |     |   borrowed value does not live long enough
  |             |     value captured here
  |             type annotation requires that `i` is borrowed for `'static`
6 |     return integrate(&f, 0.0, 100.0);
7 | }
  |  - `i` dropped here while still borrowed

For more information about this error, try `rustc --explain E0597`.

我检查了这个箱子是如何实现的。这是一个更简单的代码,解释了内部发生的事情:

pub use std::rc::Rc;
pub type Function = Rc<dyn Fn(f64) -> f64>;

#[macro_export]
macro_rules! func {
    ($e:expr) => (Rc::new($e) as Function);
}

fn print_3_next_numbers(i: f64) {
    let f = func!(|x| 1.0 + x);
    println!("The next +1 number is: {}", f(1.0));
    println!("The next +2 number is: {}", f(2.0));
    println!("The next +3 number is: {}", f(3.0));
}


fn main() {
    print_3_next_numbers(50.0);
}

如何用铁锈做到这一点?

rust rust-cargo
1个回答
0
投票

类型别名

Function
Rc<dyn Fn(f64) -> f64>
,这要求包装函数是
'static
(不捕获任何生命周期)。但是您创建的闭包捕获了
i
。您可以强制关闭以获取 i
所有权
并将其
move
放入关闭中。


fn calc(i: f64) -> f64 {
    let f = func!(move |x| i + x);
    return integrate(&f, 0.0, 100.0);
}
© www.soinside.com 2019 - 2024. All rights reserved.