# Trait associated type lifetime issues

**URL:** <https://users.rust-lang.org/t/trait-associated-type-lifetime-issues/58491>\
**Category:** help\
**Created:** [April 16, 2021, 11:48am UTC](https://users.rust-lang.org/t/trait-associated-type-lifetime-issues/58491 "2021-04-16T11:48:14Z")\
**Posts on this page:** 6\
**Page:** 1

<div class="post-metadata">

**Author:** ![realcr](https://sea1.discourse-cdn.com/flex019/user_avatar/users.rust-lang.org/realcr/32/4676_2.png) [@realcr](https://users.rust-lang.org/u/realcr)\
**Post date:** [April 16, 2021, 11:48am UTC](https://users.rust-lang.org/t/trait-associated-type-lifetime-issues/58491/1 "2021-04-16T11:48:14Z")

</div>

I have issues creating the correct function signature when working with a trait that is generic over a lifetime. [Playground link](https://play.rust-lang.org/?version=stable&mode=debug&edition=2018&gist=0459440f4620a59d46f23b81b9652a69)  
This is what the trait looks like (constructed based on idea here: [rust - How do I specify lifetime parameters in an associated type? - Stack Overflow](https://stackoverflow.com/a/33756123))

```rust
trait MyTrait<'a> {
    type MyType;

    fn get_my_type(&'a mut self) -> Self::MyType;
}

```

And this is the function that does not compile:

```rust
fn func2<'a, T: MyTrait<'a>>(mut a: T) {
    a.get_my_type();
}

```

I was wondering if there is any way to fix the function signature to make it compile?  
Currently all that I managed to do is either:

- Use the concrete type as argument (which defeats the whole purpose of the trait abstraction)
- Change the function's signature to accept a mutable reference to T instead of taking ownership of T. Maybe this could somehow be enough for my project? I have a hunch that somewhere along the way I might need to take ownership over object.

Compiler error:

```rust
error[E0309]: the parameter type `T` may not live long enough
  --> src/main.rs:44:5
   |
43 | fn func2<'a, T: MyTrait<'a>>(mut a: T) {
   | -- help: consider adding an explicit lifetime bound...: `T: 'a +`
44 | a.get_my_type();
   | ^ ...so that the type `T` is not borrowed for too long

error[E0309]: the parameter type `T` may not live long enough
  --> src/main.rs:44:7
   |
43 | fn func2<'a, T: MyTrait<'a>>(mut a: T) {
   | -- help: consider adding an explicit lifetime bound...: `T: 'a +`
44 | a.get_my_type();
   | ^^^^^^^^^^^ ...so that the reference type `&'a mut T` does not outlive the data it points at

```

For reference, I include a full self contained example:

```rust
trait MyTrait<'a> {
    type MyType;

    fn get_my_type(&'a mut self) -> Self::MyType;
}

struct MyStruct {
    num: u32,
}

struct MyTypeStruct<'a> {
    num: &'a mut u32,
}

impl<'a> MyTrait<'a> for MyStruct {
    type MyType = MyTypeStruct<'a>;

    fn get_my_type(&'a mut self) -> Self::MyType {
        MyTypeStruct { num: &mut self.num }
    }
}

// Compiles when specifying the struct name directly.
fn func1(mut a: MyStruct) {
    a.get_my_type();
}

// Does not compile:
fn func2<'a, T: MyTrait<'a>>(mut a: T) {
    a.get_my_type();
}

fn main() {
    let mut my_struct = MyStruct { num: 3 };
    let my_type_struct = my_struct.get_my_type();
    *my_type_struct.num = 4;
    println!("{}", my_struct.num);
}

```

**Edit**  
Here as an example for a function that borrows T instead of taking ownership:

```rust
fn func3<'a, T: MyTrait<'a>>(a: &'a mut T) {
    a.get_my_type();
}

```

It compiles, but I am pretty sure at some point, possibly at one of the callers, I will need to take ownership over the generic T.

---

<div class="post-metadata">

**Author:** ![steffahn](https://sea1.discourse-cdn.com/flex019/user_avatar/users.rust-lang.org/steffahn/32/47569_2.png) [@steffahn](https://users.rust-lang.org/u/steffahn)\
**Post date:** [April 16, 2021, 12:01pm UTC](https://users.rust-lang.org/t/trait-associated-type-lifetime-issues/58491/2 "2021-04-16T12:01:51Z")

</div>

The problem is that the lifetime parameter of `func2` does not match up with the lifetime of the borrow of the local variable `a`. In particular, lifetime parameters such as `'a` will always refer to lifetimes that are _longer_ than the duration of the function call, whereas the local variable can only be borrowed for _shorter_ than the duration of the function call.

The solution that Rust offers is HRTBs (higher rank trait bounds). [Page in the nomicon](https://doc.rust-lang.org/nomicon/hrtb.html#higher-rank-trait-bounds-hrtbs). [Section in the reference](https://doc.rust-lang.org/reference/trait-bounds.html#higher-ranked-trait-bounds). You just assert the trait bound `T: MyTrait<'a>` for _all_ lifetimes `'a`, and that way the lifetime of the short, local borrow is also applicable. The signature becomes

```rust
fn func2<T: for<'a> MyTrait<'a>>(mut a: T) {
    a.get_my_type();
}

// alternative syntax with the `for` coming first, in where clauses
fn func2<T>(mut a: T)
where
    for<'a> T: MyTrait<'a>
// you can still also write
// T: for<'a> MyTrait<'a>
// instead
{
    a.get_my_type();
}

```

---

<div class="post-metadata">

**Author:** ![Yandros](https://sea1.discourse-cdn.com/flex019/user_avatar/users.rust-lang.org/yandros/32/8136_2.png) [@Yandros](https://users.rust-lang.org/u/Yandros)\
**Post date:** [April 16, 2021, 12:33pm UTC](https://users.rust-lang.org/t/trait-associated-type-lifetime-issues/58491/3 "2021-04-16T12:33:56Z")

</div>

This is something that GATs will make more ergonomic. In the meantime, I recommend the following setup (which is basically akin [to `Deserialize<'de> / DeserializeOwned` in `serde`](https://serde.rs/lifetimes.html)):

```rust
/// Trait used to write the `impl`s
trait MyTrait_<'a> {
    type MyType /* : bounds… */ ; // You will probably need to add bounds here when doing HRTB…

    fn get_my_type (self: &'a mut Self)
      -> Self::MyType
    ;
}

/// Trait alias to be used in bounds.
trait MyTrait
where
    for<'any> Self : MyTrait_<'any>,
{}
    impl<T : ?Sized> MyTrait for T
    where
        for<'any> Self : MyTrait_<'any>,
    {}

```

- 

> **GAT version**
>
> ```rust
> trait MyTrait {
> type MyType<'a>;
> 
> fn get_my_type<'a> (self: &'a mut Self)
> -> Self::MyType<'a>
> ;
> }
> 
> ```

That way, you can write:

```rust
struct MyStruct {
    num: u32,
}

struct MyTypeStruct<'a> {
    num: &'a mut u32,
}

impl<'a> MyTrait_<'a> for MyStruct {
    type MyType = MyTypeStruct<'a>;

    fn get_my_type (self: &'a mut MyStruct)
      -> MyTypeStruct<'a>
    {
        MyTypeStruct { num: &mut self.num }
    }
}

fn func2<T : MyTrait> (mut a: T)
{
    a.get_my_type();
}

fn func1 (a: MyStruct)
{
    func2(a) // OK
}

```

---

<div class="post-metadata">

**Author:** ![EdmundsEcho](https://sea1.discourse-cdn.com/flex019/user_avatar/users.rust-lang.org/edmundsecho/32/18445_2.png) [@EdmundsEcho](https://users.rust-lang.org/u/EdmundsEcho)\
**Post date:** [April 16, 2021, 12:36pm UTC](https://users.rust-lang.org/t/trait-associated-type-lifetime-issues/58491/4 "2021-04-16T12:36:18Z")

</div>

@steffahn your solution works. Is there a way to specify the lifetime requirement in the associated type itself? The gap in lifetimes is apparent in the trait definition.

---

<div class="post-metadata">

**Author:** ![steffahn](https://sea1.discourse-cdn.com/flex019/user_avatar/users.rust-lang.org/steffahn/32/47569_2.png) [@steffahn](https://users.rust-lang.org/u/steffahn)\
**Post date:** [April 16, 2021, 12:48pm UTC](https://users.rust-lang.org/t/trait-associated-type-lifetime-issues/58491/5 "2021-04-16T12:48:20Z")

</div>

In case that wasn’t clear, what @Yandros is suggesting is to introduce a [shorthand/alias](https://www.worthe-it.co.za/blog/2017-01-15-aliasing-traits-in-rust.html) for the HRTB `for<'a> MyTrait<'a>`. Furthermore the suggestion was to name this shorthand `MyTrait` and name the original trait `MyTrait_` instead.

The

```rust
trait MyTrait
where
    for<'any> Self : MyTrait_<'any>,
{}

```

definition is equivalent to

```rust
trait MyTrait: for<'a> MyTrait<'a>
{}

```

so the HRTB becomes a “supertrait”, hence `T: MyTrait` bounds in a function _imply_ that you have `T: for<'a> MyTrait_<'a>` available. The two bounds `MyTrait` and `for<'a> MyTrait<'a>` become fully equivalent by the additional “blanket implementation”

```rust
    impl<T : ?Sized> MyTrait for T
    where
        for<'any> Self : MyTrait_<'any>,
    {}

```

which is equivalent to

```rust
impl<T: ?Sized> MyTrait for T
where
    T: for<'a> MyTrait_<'a>,
{}

```

this way, `T: for<'a> MyTrait_<'a>` also implies `T: MyTrait`.

This is analogous to what serde does, in the case of serde, `DeserializeOwned` is a shorthand for `for<'de> Deserialize<'de>`. You can see the supertrait and the blanket implementation [in the docs](https://docs.serde.rs/serde/de/trait.DeserializeOwned.html) (expand “Show declaration” to see supertraits).

---

<div class="post-metadata">

**Author:** ![system](https://sea1.discourse-cdn.com/flex019/user_avatar/users.rust-lang.org/system/32/51372_2.png) [@system](https://users.rust-lang.org/u/system)\
**Post date:** [July 15, 2021, 12:49pm UTC](https://users.rust-lang.org/t/trait-associated-type-lifetime-issues/58491/6 "2021-07-15T12:49:18Z")

</div>

Closed on July 15, 2021, 12:49pm UTC

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.
