-
Notifications
You must be signed in to change notification settings - Fork 12.7k
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
How to correct "prior loan as mutable" error with subsequent method calls? #5829
Comments
I've run into a lot of similar errors, and the common case which I've seen is that the compiler really doesn't like borrowed pointers in structs with mutable methods. Even something as simple as below fails to compile: struct Foo<'self> {
a: &'self int
}
impl<'self> Foo<'self> {
fn foo(&mut self) {}
}
fn main() {
let n = 1;
let mut foo = Foo { a: &n };
foo.foo();
foo.foo();
} I'm not sure if this is an actual error or some bug in the compiler, but I do agree that the error message could probably be more helpful. |
This is correct. The problem is that the lifetime of the borrow is the same as a lifetime that escapes the function call, in this case via a mutable field, and therefore it persists for the lifetime of the mutable field. Consider this code: struct T<'self> {
x: &'self mut int,
y: int,
}
fn F1<'a>(t: &'a mut T<'a>) {
*&mut t.x = &mut t.y;
}
fn F2<'a, 'b>(_t: &'a mut T<'b>) {
}
fn main() {
let mut x = 5;
let mut t = T{x: &mut x, y: 6};
F2(&mut t);
F2(&mut t);
} In Unfortunately, this trick doesn't quite work yet in rust-0.6 when it comes to methods because of how the lifetime of the |
This is fixed thanks to all the work @nikomatsakis did on making the |
Use `(std::)f64::EPSILON` in the examples as suggested in the lints `float_cmp(_const)` suggests using `{f32|f64}::EPSILON` and it'd be great if the docs mentioned it. changelog: none
Using rust 0.6 from homebrew. Trying to do two subsequent method calls with a mutable borrowed self -- by contrast, any number of calls to "peek" seem to work okay:
(I may be doing it wrong but I figured making a github issue would at least make the fix searchable. :-)
The text was updated successfully, but these errors were encountered: