Adam
Adam

Reputation: 1009

What lifetime does this function have when not annotated?

I'm learning Rust and I wrote this somewhat contrived example.

#[derive(Debug)]
struct Foo<'a> {
    x: i32,
    s: &'a String,
}

impl<'a> Foo<'a> {
    fn new(s: &String) -> Foo {
        Foo {
            x: 0,
            s,
        }
    }

    fn inc_and_return<'b>(&mut self, s: &'b str) -> &'b str {
        self.x += 1;
        s
    }
}

fn main() {
    let hello = String::from("hello");
    let mut f = Foo::new(&hello);
    println!("{}", f.inc_and_return("one"));
    println!("{}", f.s);
}

This works. However, when I add what I thought was the implicit lifetime to self, it errors out:

fn inc_and_return<'b>(&'a mut self, s: &'b str) -> &'b str {
    self.x += 1;
    s
}

When I do this, I cannot access f.s with the error cannot borrow `f.s` as immutable because it is also borrowed as mutable.

I'm confused: yes, I borrowed it, but I don't keep that reference around, and I thought I was explicitly telling the compiler that by adding in 'a. So my question is

  1. What are the actual lifetimes associated with inc_and_return when I don't fully annotate it?
  2. What does it mean to refer to 'a in a fn in an impl<'a> Foo<'a>?

Upvotes: 0

Views: 48

Answers (0)

Related Questions