Skip to content

Instantly share code, notes, and snippets.

@MarkJr94
Created June 28, 2013 21:57
Show Gist options
  • Save MarkJr94/5888472 to your computer and use it in GitHub Desktop.
Save MarkJr94/5888472 to your computer and use it in GitHub Desktop.
Minimal example of problem with borrowck, mutability, and trait objects.
// traitfail.rs
trait Slide {
fn new(x: int) -> Self;
fn x_mut<'r> (&'r mut self) -> &'r mut int;
fn x(&self) -> int;
}
struct Bead {
x: int
}
impl Slide for Bead {
pub fn new(x: int) -> Bead {
Bead { x: x}
}
pub fn x(&self) -> int {
self.x
}
pub fn x_mut<'r>(&'r mut self) -> &'r mut int {
&'r mut self.x
}
}
fn main() {
let slide = &mut Slide::new::<Bead>(5) as &mut Slide;
let x = slide.x();
let x_mut = slide.x_mut();
*x_mut += 2;
}
// Compiler output
traitfail.rs:30:13: 30:18 error: cannot borrow immutable local variable as mutable
traitfail.rs:30 let x_mut = slide.x_mut();
^~~~~
error: aborting due to previous error
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment