我有一个普通的Interface号特征.Interface有一个method,它将使用动态调度来调用.具体地说,我将在Rc<RefCell<dyn Interface>>岁左右通过.

我有一个用例,其中我需要将对method的调用包装在闭包中.所需的行为是使用input调用闭包将与使用input调用obj.method相同,其中obj实现Interface.

以下是我到目前为止的try .

use std::cell::RefCell;
use std::rc::Rc;

pub trait Interface<'p, T> {
    fn method<'s: 'p>(&'p self, input: &'s str) -> T;
}

fn wrap_interface_with_closure<'p, 's: 'p, T: 'p>(
    instance: Rc<RefCell<dyn Interface<'p, T>>>,
) -> impl FnMut(&'s str) -> T + 'p {
    move |input| (*instance).borrow().method(input)
}

这会给我带来以下错误:

error[E0716]: temporary value dropped while borrowed
   |
13 |     instance: Rc<RefCell<dyn Interface<'p, T>>>,
   |     -------- lifetime `'2` appears in the type of `instance`
14 | ) -> impl FnMut(&'s str) -> T + 'p {
15 |     move |input| (*instance).borrow().method(input)
   |                  ^^^^^^^^^^^^^^^^^^^^--------------
   |                  |                                |
   |                  |                                temporary value is freed at the end of this statement
   |                  creates a temporary which is freed while still in use
   |                  argument requires that borrow lasts for `'2`

error: lifetime may not live long enough
   |
13 |     instance: Rc<RefCell<dyn Interface<'p, T>>>,
   |     -------- lifetime `'2` appears in the type of `instance`
14 | ) -> impl FnMut(&'s str) -> T + 'p {
15 |     move |input| (*instance).borrow().method(input)
   |     ------------   ^^^^^^^^ closure capture requires that `'1` must outlive `'2`
   |     |
   |     lifetime `'1` represents this closure's body
   |
   = note: closure implements `FnMut`, so references to captured variables can't escape the closure

error: aborting due to 2 previous errors; 2 warnings emitted

当它说closure implements FnMut, so references to captured variables can't escape the closure时,它指的是哪个捕获的变量?是不是说instance号逃走了?这是否意味着借款正在逃逸?

推荐答案

你的性状需要&'p self,即self的引用必须与'p相同.在您的闭包中,您可以调用borrow():

(*instance).borrow()

您将获得对接口的引用,该接口的生命周期仅持续整个闭包('1).然而,您的性状定义要求self的生命周期 为'p:

fn method<'s: 'p>(&'p self, input: &'s str) -> T;

因此,当您在闭包中调用.method()时,self的生存期将是'1(在闭包内有效),它的生存期不足以满足您的参数的生存期'p.您可以通过删除对SELF的要求来修复此问题:

fn method<'s: 'p>(&self, input: &'s str) -> T;

你仍然可以确定input比你的instance更长寿,因为's :'p是你wrap_interface_with_closure功能的一部分.

Rust相关问答推荐

使用nom将任何空白、制表符、白线等序列替换为单个空白

如何创建引用构造函数拥有的变量的对象?

JSON5中的变量类型(serde)

我如何使用AWS SDK for Rust获取我承担的角色的凭据?

为什么`str`类型可以是任意大小(未知大小),而`string`类型的大小应该是已知的?

使用关联类型重写时特征的实现冲突

Rust Axum 框架 - 解包安全吗?

在 Rust 中忽略 None 值的正确样式

go 重并堆积MPSC通道消息

全面的 Rust Ch.16.2 - 使用捕获和 const 表达式的 struct 模式匹配

实现泛型的 Trait 方法中的文字

当 T 不是副本时,为什么取消引用 Box 不会抱怨移出共享引用?

在 Rust 中如何将值推送到枚举 struct 内的 vec?

如果我不想运行析构函数,如何移出具有析构函数的 struct ?

火箭整流罩、tokio-scheduler 和 cron 的生命周期问题

在使用大型表达式时(8k 行需要一小时编译),是否可以避免 Rust 中的二次编译时间?

`if let` 只是另一种编写其他 `if` 语句的方式吗?

在 Rust 中有条件地导入?

Rust 中的运行时插件

来自外部函数的future 内部可变引用