Skip to content

Instantly share code, notes, and snippets.

@mitchmindtree
Created June 8, 2014 10:59
Show Gist options
  • Save mitchmindtree/e9157d1e32005cd60910 to your computer and use it in GitHub Desktop.
Save mitchmindtree/e9157d1e32005cd60910 to your computer and use it in GitHub Desktop.
A question regarding good practice and impl'ing trait methods that return a mutable reference to self.
// Is it considered bad practise to do something like this?
// Or is it fine? Common even?
//
// I'm specifically referring to impl'ing a trait method for a
// struct that returns a mutable reference to itself? In my
// current situation, it seems it will save a lot of unnecessary
// impl'ing when deriving from trait "A".
#[deriving(Show)]
pub struct MyStruct<'a> { i: int }
pub trait A<'a> {
fn get_mystruct(&'a mut self) -> &'a mut MyStruct;
// Heaps of other fn's referring to 'get_mystruct'...
}
impl<'a> A<'a> for MyStruct<'a> {
fn get_mystruct(&'a mut self) -> &'a mut MyStruct { self }
}
fn main() {
let mut ms = MyStruct { i: 25 };
println!("{}", ms);
println!("{}", ms.get_mystruct());
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment