How do you borrow a mutable pointer in rust? -


i have function returns result<&'a ~foo, barerr>, can access using:

match x.borrow() {   ok(ref foo) => println!("found {}", foo.value),   err(nope) => println!("bleh") } 

however, find myself in more complex situation in wish borrow mutable reference instead, such might able call function on it:

match x.borrow() {   ok(ref foo) => { foo.inc(); trace!("found {}", foo.value); },   err(nope) => trace!("bleh") } 

i've tried few variations on need stick 'mut' in, such mut ref foo, ref mut foo, -> mut result<...>, -> result, can't seem figure out syntax required.

i keep getting:

error: cannot borrow immutable dereference of `~`-pointer `***foo` mutable 

what should be?

complete code example:

macro_rules! trace(   ($($arg:tt)*) => (     { let x = ::std::io::stdout().write_line(format_args!(::std::fmt::format, $($arg)*)); println!("{}", x); }   ); )  #[deriving(show)] struct foo {   value: int }  impl foo {   fn inc(&mut self) {     self.value += 1;   } }  #[deriving(show)] struct bar {   data: option<~foo> }  #[deriving(show)] enum barerr {   nope }  impl bar {   fn borrow<'a>(&'a mut self) -> result<&'a ~foo, barerr> {     match self.data {       some(ref e) => return ok(e),       none => return err(nope)     }   } }  #[test] fn test_create_indirect() {   let y = ~foo { value: 10 };   let mut x = bar { data: some(y) };   let mut x2 = bar { data: none };   {     match x.borrow() {       ok(ref mut foo) => { foo.inc(); trace!("found {}", foo.value); },       err(nope) => trace!("bleh")     }   }   {     let z = x2.borrow();     trace!("z: {}", z);   } } 

the problem references not own data, hence mutability inherited. cannot turn &'a &'a mut, because data under reference immutable.

you have return result<&'a mut ~foo, barerr> in order achieve want:

impl bar {   fn borrow<'a>(&'a mut self) -> result<&'a mut ~foo, barerr> {     match self.data {       some(ref mut e) => return ok(e),       none => return err(nope)     }   } }  #[test] fn test_create_indirect() {   let y = ~foo { value: 10 };   let mut x = bar { data: some(y) };   let mut x2 = bar { data: none };   {     match x.borrow() {       ok(foo) => { foo.inc(); trace!("found {:?}", foo.value); },       err(nope) => trace!("bleh")     }   }   {     let z = x2.borrow();     trace!("z: {:?}", z);   } } 

note @ usage site i'm matching x.borrow() against ok(foo), not ok(ref mut foo). that's ok because foo &mut, can access &mut self methods through it.


Comments

Popular posts from this blog

Android layout hidden on keyboard show -

google app engine - 403 Forbidden POST - Flask WTForms -

c - Why would PK11_GenerateRandom() return an error -8023? -