Skip to content

Instantly share code, notes, and snippets.

@mitchmindtree
Last active August 29, 2015 14:02
Show Gist options
  • Save mitchmindtree/a23aad5ac762513807ab to your computer and use it in GitHub Desktop.
Save mitchmindtree/a23aad5ac762513807ab to your computer and use it in GitHub Desktop.
Defining "setter" methods within a trait.
// The example below gives the following:
//
// "error: cannot borrow `*self` as mutable more than once at a time"
//
// I understand why, but I am wondering if it is possible to define
// "setter" methods within the trait in a way similar to this?
#[deriving(Show)]
pub struct MyStruct<'a> { i: int, j: int }
pub trait A<'a> {
fn get_mystruct(&'a mut self) -> &'a mut MyStruct;
fn set_with_i(&'a mut self, i: int) {
self.get_mystruct().i = i;
self.get_mystruct().j = i*2; // "error: cannot borrow `*self` as mutable more than once at a time"
}
fn set_with_j(&'a mut self, j: int) {
self.get_mystruct().j = j;
self.get_mystruct().j = j/2; // "error: cannot borrow `*self` as mutable more than once at a time"
}
}
impl<'a> A<'a> for MyStruct<'a> {
fn get_mystruct(&'a mut self) -> &'a mut MyStruct { self }
}
@mitchmindtree
Copy link
Author

SOLVED! By removing the lifetimes from the setter function arguments and adding a lifetime parameter to get_mystruct.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment