如何将方法传递给需要静态生命周期参数的函数?

How do I pass a method to a function requiring a static lifetime parameter?

考虑到函数需要 "handler" 和静态生命周期,我如何将方法传递给函数?

(这背后的确切用例是在结构中创建 Iron 链)。

考虑到我们有以下结构 Chain:

struct Chain
{
    f: Box<dyn Fn()>
}

impl Chain
{
    fn new(handler: impl Fn() + 'static) -> Self
    {
        return Chain { f: Box::new(handler) };
    }

    fn invoke(&self)
    {
        (self.f)();
    }
}

当尝试使用闭包创建此 Chain 的实例时,同时还在闭包中传递方法...

struct MyStruct
{
    the_answer: u32
}

impl MyStruct
{
    pub fn run(&self)
    {
        let closure = || {
            println!("Closure called");
            self.printer_method(String::from("printer_method")); // <-- Problematic line
        };

        let chain = Chain::new(closure);

        chain.invoke();
    }

    fn printer_method(&self, msg: String)
    {
        // Access to self.the_answer
        println!("The answer is {}, your message is: {}", self.the_answer, msg);
    }
}

...编译器给出以下错误:

error[E0495]: cannot infer an appropriate lifetime due to conflicting requirements

我曾尝试过将 MyStruct 及其成员声明为静态的想法,但必须能够创建该结构的多个独立实例(参见多个实例的结构钢铁网络服务器)。

这里是 Playground link

在你的闭包中:

let closure = || {
    println!("Closure called");
    self.printer_method(String::from("printer_method")); // <-- here
};

由于方法调用,您正在捕获 &MyStruct。由于 Rust 中的闭包基本上只是具有 "call" 方法的结构,因此该闭包不能是“静态的”,因为它会比对 MyStruct 的引用更有效。解决方案是在此生命周期内获得通用性:

struct Chain<'a>
{
    f: Box<dyn Fn() +'a>
}

impl<'a> Chain<'a>
{
    fn new(handler: impl Fn() + 'a) -> Self
    {
        return Chain { f: Box::new(handler) };
    }

    fn invoke(&self)
    {
        (self.f)();
    }
}