Skip to content

Instantly share code, notes, and snippets.

@yonran
Last active December 24, 2015 02:29
Show Gist options
  • Save yonran/6730835 to your computer and use it in GitHub Desktop.
Save yonran/6730835 to your computer and use it in GitHub Desktop.
Rust: cannot assign to `(*self).count` because it is borrowed
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));
}
@yonran
Copy link
Author

yonran commented Sep 27, 2013

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?

@yonran
Copy link
Author

yonran commented Sep 27, 2013

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