1

I have a newtype struct:

pub struct Branch<'repo>(Git2Branch<'repo>);

And I am trying to wrap a method call:

impl <'repo> Branch<'_> {
    pub fn into_reference(self) -> Git2Reference<'repo> {
        self.0.into_reference()
    }    
}

(Git2Branch and Git2Reference here are aliases for types of the same name from the git2 crate.)

This fails to compile with

error: lifetime may not live long enough
  --> git_wrapper/src/branch.rs:38:9
   |
6  | impl <'repo> Branch<'_> {
   |       ----- lifetime `'repo` defined here
...
37 |     pub fn into_reference(self) -> Git2Reference<'repo> {
   |                           ---- has type `branch::Branch<'1>`
38 |         self.0.into_reference()
   |         ^^^^^^^^^^^^^^^^^^^^^^^ associated function was supposed to return data with lifetime `'repo` but it is returning data with lifetime `'1`

Lifetimes '1 and 'repo should be the same, but I can't figure out how (or if it's even possible) to specify the lifetime of self in this case.

Tim Keating
  • 6,443
  • 4
  • 47
  • 53

1 Answers1

3
impl <'repo> Branch<'_> {

Is the same as:

impl <'repo, 'anonymous> Branch<'anonymous> {

So the lifetimes 'repo and the anonymous lifetime of the field are unrelated - which causes an issue when you try to return the Git2Reference<'anonymous>.

You only need to talk about one lifetime here, so say that:

impl <'repo> Branch<'repo> {
Colonel Thirty Two
  • 23,953
  • 8
  • 45
  • 85