Skip to content

Commit f4b5516

Browse files
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

File tree

1 file changed

+1
-1
lines changed

1 file changed

+1
-1
lines changed

src/branch.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -73,7 +73,7 @@ impl<'repo> Branch<'repo> {
7373

7474
/// Return the reference supporting the remote tracking branch, given a
7575
/// local branch reference.
76-
pub fn upstream<'a>(&'a self) -> Result<Branch<'a>, Error> {
76+
pub fn upstream<'a>(&self) -> Result<Branch<'a>, Error> {
7777
let mut ret = ptr::null_mut();
7878
unsafe {
7979
try_call!(raw::git_branch_upstream(&mut ret, &*self.get().raw()));

0 commit comments

Comments
 (0)