1

I have a struct that I implement Deref on:

pub struct Foo {
    val: u8,
}

impl Deref for Foo {
    type Target = u8;

    fn deref(&self) -> &u8 {
        &self.val
    }
}

I want to change the struct internally so that the value is held in a Cell:

pub struct Foo {
    val: Cell<u8>,
}

I've naively implemented Deref as follows:

impl Deref for Foo {
    type Target = u8;

    fn deref(&self) -> &u8 {
        &self.val.get()
    }
}

The compiler complains saying &self.val.get() does not live long enough, which mostly makes sense to me (Cell not being a Copy type?), but I have no idea how to get it to compile. I've tried annotating with lifetimes, but what I'm doing doesn't feel intuitively correct and I'm just blindly changing stuff at this point.

Shepmaster
  • 388,571
  • 95
  • 1,107
  • 1,366
w.brian
  • 16,296
  • 14
  • 69
  • 118
  • 1
    Are you willing to accept "you can't" answers? Can we know why you need to have the value in a Cell? Perhaps `Deref` is not an adequate trait to impl here, but we can't be sure right now. – E_net4 Apr 10 '17 at 22:47
  • If the answer is "you can't" then I'll mark it as such. The value needs to be in a Cell because I require interior mutability here. That being said, whether or not I need a cell is out of scope for the question. – w.brian Apr 10 '17 at 22:53

1 Answers1

3

Cell allows interior mutability by never allowing you to get an immutable reference to the inner value. get returns a copy of the value, and get_mut only works if you have a mutable reference to start with.

Since all you can get is a value, and there's no way to return a reference to a local value, there's no way to implement Deref for this type.


In case you think you can "trick" the compiler by using a RefCell, you cannot, but you can wrap the Ref type that it produces:

Community
  • 1
  • 1
Shepmaster
  • 388,571
  • 95
  • 1,107
  • 1,366