2

I am trying to implement Deref for my struct:

use std::cell::{RefCell, RefMut};
use std::ops::Deref;
use std::rc::Rc;

fn main() {
    let x = VariableData {
        data: Rc::new(RefCell::new(Vec::new())),
    };

    x.push(6);
}

struct VariableData {
    data: Rc<RefCell<Vec<u32>>>,
}

impl<'a> Deref for VariableData {
    type Target = RefMut<'a, Vec<u32>>;
    fn deref(&self) -> &Self::Target {
        self.data.borrow_mut()
    }
}

But I get the following error:

error[E0207]: the lifetime parameter `'a` is not constrained by the impl trait, self type, or predicates
  --> src/main.rs:17:6
   |
17 | impl<'a> Deref for VariableData {
   |      ^^ unconstrained lifetime parameter

How do I specify that 'a is at most the lifetime of VariableData?

Shepmaster
  • 388,571
  • 95
  • 1,107
  • 1,366
Mateholiker
  • 329
  • 2
  • 9
  • 1
    No but know I noticed the problem I cannot return a RefMut struct because I need to return a reference – Mateholiker Feb 11 '20 at 17:42
  • 1
    You cannot return a reference like that, as both answers to the other question state. Also read [How do I return a reference to something inside a RefCell without breaking encapsulation?](https://stackoverflow.com/q/29401626/3650362) You must either not use `Deref`, or find a way to go without the `RefCell`. The `Drop` behavior of `RefMut` is essential to the safety provided by `RefCell`. – trent Feb 11 '20 at 17:57
  • 1
    The literal answer to your original question is "you cannot" because the `Deref` trait has defined the interface and the relevant lifetimes. It's the same as asking "how do you make `Deref::deref` return a value instead of a reference" or "return a `Result`" or "take an argument". If you did any of that, it's not the `Deref` trait anymore. – Shepmaster Feb 11 '20 at 18:24

0 Answers0