Skip to content

Mutable references in field #15868

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
tprodanov opened this issue Jul 21, 2014 · 4 comments
Closed

Mutable references in field #15868

tprodanov opened this issue Jul 21, 2014 · 4 comments
Labels
A-lifetimes Area: Lifetimes / regions

Comments

@tprodanov
Copy link

Sorry, maybe it is hundred times solved problem, but I cannot use structure filed, which is mutable reference with longer lifetime, than the structure itself. In this code

struct A<'r> {
    v: &'r mut Vec<int>
}

impl<'r> A<'r> {
    fn create(v: &'r mut Vec<int>) -> A<'r> {
        A::<'r> {
            v: v
        }
    }

    fn get_mut(&mut self, i: uint) -> &'r mut int {
        self.v.get_mut(i)
    }
}

in function get_mut I got an error, lifetime of 'self' is too short. But without all mut keywords code runs without errors.

@alexcrichton
Copy link
Member

cc @nikomatsakis

@prajwalkman
Copy link

Not sure if this solves it, but

    fn get_mut(&'r mut self, i: uint) -> &'r mut int {
        self.v.get_mut(i)
    }

compiles fine. Is the explicit lifetime on self supposed to be elided?

@tprodanov
Copy link
Author

@prajwalkman, Yes, but for example if I want to implement mutable iterator Iterator<&'r mut T> I have to write function fn next(&mut self) -> Option<&'a mut T>, so I have &mut self in argument. Maybe there is another way to do it but it is confusing that for immutable iterator Iterator<&'r T> everything works

@alexcrichton
Copy link
Member

Hm upon re-reflection I believe this is actually intended behavior. You cannot take out a mutable borrow longer than the lifetime of the mutable borrow which granted mutable access. In this case the function is trying to borrow &'a mut &'r mut int to &'r mut int (essentially), but this is can lead to safety violations later on down the road, so closing this an expected error.

bors added a commit to rust-lang-ci/rust that referenced this issue Jan 21, 2024
fix: failed to infer OUT_DIR when workspace root contains symlink

fix rust-lang#15867
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
A-lifetimes Area: Lifetimes / regions
Projects
None yet
Development

No branches or pull requests

4 participants