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 hidden or 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)); | |
} |
Asked again http://irclog.gr/#show/irc.mozilla.org/rust/847768 https://botbot.me/mozilla/rust/msg/6414381/
Rust question: If I have a match that binds a variable in a destructuring enum pattern, can I end the variable's lifetime inside the match arm, or do I have to exit the match and do a conditional afterwards?
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(_)
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I asked in #rust irc: http://irclog.gr/#show/irc.mozilla.org/rust/847489 or https://botbot.me/mozilla/rust/msg/6411983/
Hello. I'm having trouble fixing a compiler error "cannot assign to
(*self).count
because it is borrowed". Is there any way to forget a borrowed pointer without unraveling a match? util::ignore doesn't seem to do the trick.