The problem is that references do not own data, hence their mutability is inherited. You cannot turn &'a
into &'a mut
, because the data under that reference is immutable.
You have to return Result<&'a mut ~Foo, BarErr>
in order to achieve what you 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 that at the usage site I'm matching x.borrow()
against Ok(foo)
, not Ok(ref mut foo)
. That's OK because foo
itself is &mut
, so you can access &mut self
methods through it.