我有一个终生的 struct :

struct HasLifetime<'a>( /* ... */ );

有一个trait Foo的实现:

impl<'a, 'b: 'a> Foo for &'a mut HasLifetime<'b> { }

我想实现以下功能:

fn bar_to_foo<'a, 'b: 'a>(bar: &'a mut Lifetime<'b>) -> impl Foo {
    bar
}

这不会编译,因为返回的impl只对'a有效.但是,指定impl Foo + 'a会导致:

error[E0909]: hidden type for `impl Trait` captures lifetime that does not appear in bounds
 --> src/main.rs:7:60
  |
7 | fn bar_to_foo<'a, 'b: 'a>(bar: &'a mut HasLifetime<'b>) -> impl Trait + 'a {
  |                                                            ^^^^^^^^^^^^^^^
  |
note: hidden type `&'a mut HasLifetime<'b>` captures the lifetime 'b as defined on the function body at 7:1
 --> src/main.rs:7:1
  |
7 | fn bar_to_foo<'a, 'b: 'a>(bar: &'a mut HasLifetime<'b>) -> impl Trait + 'a {
  | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

带有装箱特征对象的看似等价的函数编译:

fn bar_to_foo<'a, 'b: 'a>(bar: &'a mut Lifetime<'b>) -> Box<Foo + 'a> {
    Box::new(bar)
}

我如何定义bar_to_fooimpl Trait

Playground link

推荐答案

您需要指出返回的值是基于多个生命周期构建的.但是,不能对impl Trait使用多个生存期界限,并try 对doesn't have a useful error message使用多个生存期界限.

a trick you can use种方法需要创建一个具有终生参数的虚拟特征:

trait Captures<'a> {}
impl<'a, T: ?Sized> Captures<'a> for T {}

fn bar_to_foo<'a, 'b: 'a>(bar: &'a mut HasLifetime<'b>) -> impl Trait + Captures<'b> + 'a {
    bar
}

谢天谢地,这是only occurs when the "hidden" lifetime is invariant,因为引用是可变的.

Rust相关问答推荐

如何在Rust中获得不可辩驳的'if let'模式警告Mutex锁定?""

为什么单元类型(空元组)实现了`Extend`trait?

什么是Rust惯用的方式来使特征向量具有单个向量项的别名?

铁 rust 干线无法使用PowerShell获取环境变量

有没有办法指定只在Rust的测试中有效的断言?

正则表达式中的重叠匹配?(铁 rust 正则式发动机)

如何重命名 clap_derive 中的子命令占位符?

如何在 Rust 中编写一个通用方法,它可以接受任何可以转换为另一个值的值?

具有多个键的 HashMap

如何限制 GtkColumnView 行数

为什么切片时需要参考?

我可以用 Rust 编写一个不可变变量

按下 Ctrl + C 时优雅地停止命令并退出进程

borrow 匹配手臂内部的可变

如何限制通用 const 参数中允许的值?

Rust 中 `Option` 的内存开销不是常量

使用方法、关联函数和自由函数在 Rust 中初始化函数指针之间的区别

通用函数中的生命周期扣除和borrow (通用测试需要)

在 Rust 中有条件地导入?

Rust 中的运行时插件