Commit f4b5516
committed
Relax self-borrow lifetime in Branch.upstream()
The following code currently does not compile:
```rust
fn get_upstreams<'repo>(repo: &'repo git2::Repository) ->
Vec<(git2::Branch<'repo>, Option<git2::Branch<'repo>>)>
{
repo
.branches(None) // pub fn branches(&self, filter: Option<git2::BranchType>) -> Result<git2::Branches, git2::Error>
.unwrap() // git2::Branches<'a>: Iterator<Item = Result<(git2::Branch<'repo>, git2::BranchType), git2::Error>>
.flatten() // Iterator<Item = (git2::Branch<'repo>, git2::BranchType)>
.map(|(branch, _): (git2::Branch<'repo>, _)| {
let upstream: Option<git2::Branch<'repo>> =
branch
.upstream() // pub fn upstream<'a>(&'a self) -> Result<Branch<'a>, Error>
.ok();
(branch, upstream)
}) // Iterator<Item = (git2::Branch<'repo>, git2::Branch<'repo>)>
.collect()
}
```
Error:
```
error[E0597]: `branch` does not live long enough
--> src/config/data/project.rs:49:55
|
49 | let upstream: Option<git2::Branch<'repo>> = branch.upstream().ok();
| ^^^^^^ borrowed value does not live long enough
...
58 | })
| - borrowed value only lives until here
|
note: borrowed value must be valid for the lifetime 'repo as defined on the method body at 39:30...
--> src/config/data/project.rs:39:30
|
39 | fn local_branches_internal<'repo>(&self, repo: &'repo git2::Repository) -> Result<Vec<(Branch, git2::Branch<'repo>, Option<git2::Branch<'repo>>)>, git2::Error> {
```
This is because the `.upstream()` method is declared with the same
self-borrow lifetime as the return value:
```rust
pub fn upstream<'a>(&'a self) -> Result<Branch<'a>, Error> { /* ... */ }
```
which means that the `.upstream()` call is still borrowing `self` even
after it returns, even though it returns an owned value and not a
reference. Relaxing the self-borrow lifetime allows the above code
sample to compile successfully. The lifetime of the (maybe) returned
upstream `Branch` will also be that of the repository, but otherwise
unrelated to the lifetime of the `Branch` that constructed it.1 parent 2ff823a commit f4b5516
1 file changed
+1
-1
lines changed| Original file line number | Diff line number | Diff line change | |
|---|---|---|---|
| |||
73 | 73 | | |
74 | 74 | | |
75 | 75 | | |
76 | | - | |
| 76 | + | |
77 | 77 | | |
78 | 78 | | |
79 | 79 | | |
| |||
0 commit comments