Last active
December 24, 2015 02:29
-
-
Save yonran/6730835 to your computer and use it in GitHub Desktop.
Rust: cannot assign to `(*self).count` because it is borrowed
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
use std::util; | |
struct Bar; | |
struct Foo { | |
test: bool, | |
count: int, | |
bar: Bar, | |
} | |
impl Foo { | |
fn bar_if_test<'r>(&'r self) -> Option<&'r Bar> { | |
match self.test { | |
false => None, | |
true => Some(&self.bar), | |
} | |
} | |
// This fails to compile | |
fn increment_if_test(&mut self) { | |
match self.bar_if_test() { | |
// ^~~~~ note: borrow of `(*self).count` occurs here | |
None => {}, | |
Some(bar) => { | |
// do something with bar... | |
util::ignore(bar); | |
self.count+= 1; // error: cannot assign to `(*self).count` because it is borrowed | |
} | |
} | |
} | |
/* | |
// This compiles, but I would prefer not to unravel the match if possible. | |
fn increment_if_test(&mut self) { | |
let some: bool; | |
match self.bar_if_test() { | |
None => { | |
some = false; | |
}, | |
Some(bar) => { | |
some = true; | |
} | |
} | |
if some { | |
self.count += 1; | |
} | |
} | |
*/ | |
} | |
#[main] | |
fn main() { | |
let mut foo = Foo{test:true,count:0,bar:Bar}; | |
foo.increment_if_test(); | |
println(format!("count={}", foo.count)); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Response: Looks like you have to exit the curly braces to end the variable’s lifetime. So in order to forget a variable, you have to use more curly braces than the equivalent C code. Note that if you don’t need to use the variable at all, you can avoid binding it entirely by using a pattern with a placeholder
Some(_)