Returned reference independent of parameter

fn foo<'a>(&self, arg: &’a mut Type) → &’a mut Type {
    // …
    return arg;
}

This demands &self outlives ’a . Is there any way or any planned way to specify that the return is independent of the lifetime of the first argument?

It doesn't, but what makes you think so?

Here's a playground example:

#[derive(Debug)]
struct Type;

#[derive(Debug)]
struct Foo;

impl Foo {
    fn foo<'a>(&self, arg: &'a mut Type) -> &'a mut Type {
        dbg!(self, &*arg);
        return arg;
    }
}

fn temp(arg: &mut Type) -> &mut Type {
    let temp = Foo;
    temp.foo(arg)
    // temp is dropped, so it clearly doesn't outlive arg
}

fn main() {
    dbg!(temp(&mut Type));
}
2 Likes

I left the lifetime off the return in the trait.

fn write_into<'a, W: Write>(&self, buf: &'a mut W) -> Result<&mut W>;
error: lifetime may not live long enough
  --> src/codec.rs:92:3
   |
91 |     fn write_into<'a, W: Write>(&self, buf: &'a mut W) -> Result<&'a mut W> {
   |                   --            - let's call the lifetime of this reference `'1`
   |                   |
   |                   lifetime `'a` defined here
92 |         (**self).write_into(buf)
   |         ^^^^^^^^^^^^^^^^^^^^^^^^ method was supposed to return data with lifetime `'a` but it is returning data with lifetime `'1`

:sweat_smile: error is a bit deceptive.

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.