rust - 如何获得impl Trait使用适当的生存期来对其中包含另一个生存期的值进行可变引用?

标签 rust lifetime

我有一个终身的结构:

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

有一个特质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_foo定义impl Trait

Playground link

最佳答案

您需要指出返回的值是建立在多个生存期上的。但是,您不能将多个生存期限制与impl Trait一起使用,并尝试使用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 - 如何获得impl Trait使用适当的生存期来对其中包含另一个生存期的值进行可变引用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64119848/

相关文章:

c# - DbContext Unity 不调用 HttpContextLifetimeManager.RemoveValue() 坏事?

rust - 拥有值的矛盾 "missing lifetime specifier"错误

io - 我应该如何阅读有关字节序的文件内容?

macros - 如何将 Rust 宏变量嵌入到文档中?

random - 特征界限不满足库中的错误

c# - xml配置文件中unity : pass parameters to custom lifetime constructor,

rust - 使用引用匹配结构

rust - 如何编写一个宏来返回基于字符串的结构的实现方法?

rust - 如何为构建器提供可变引用,但仅提供对构建对象的不可变引用?

reference - 迭代器通过引用返回项目,生命周期问题