2

I'm implementing a trait for VirtualTapInterface. The receive function of this trait should create a TxToken struct, where the lower property must be an Rc<RefCell<VirtualTapInterface>> containing the current VirtualTapInterface, that is self

impl<'a> Device<'a> for VirtualTapInterface {
    type TxToken = TxToken;

    fn receive(&'a mut self) -> Option<(Self::RxToken, Self::TxToken)> {
                let tx = TxToken { lower: Rc::new(RefCell::new(*self))};

I tried this but I get that

cannot move out of *self which is behind a mutable reference

move occurs because *self has type phy::virtual_tun::VirtualTapInterface, which does not implement the Copy traitrustc(E0507)

How is it possible to create a Rc<RefCell<>> of a self mutable reference?

trent
  • 25,033
  • 7
  • 51
  • 90
Guerlando OCs
  • 1,886
  • 9
  • 61
  • 150

1 Answers1

2

I think you need to change the signature to fn receive(self) -> ... to take ownership. Cloning or taking a box could also work.

Another option is to use mem::take, mem::replace, or mem::swap.

Solomon Ucko
  • 5,724
  • 3
  • 24
  • 45
  • I cannot change the signatures, they're from a Trait. What you mean cloning? From what? – Guerlando OCs May 26 '20 at 18:59
  • Using `self.clone()` instead of `*self` (if possible). – Solomon Ucko May 26 '20 at 19:00
  • cloning will create a copy, right? I need to have a reference to the same object, so cloning is not an option. – Guerlando OCs May 26 '20 at 23:02
  • @GuerlandoOCs Yeah. Would one of the `mem::*` functions work? It's not possible to have an `Rc>` to an unowned object. – Solomon Ucko May 27 '20 at 00:18
  • @GuerlandoOCs To be able to use `Rc>` you need to ownership, which means you need to either take ownership by using one of the `mem::*` functions or cloning the object, or you need to already have ownership, by taking `self` or `self: Box` instead of `&mut self`. – Solomon Ucko May 27 '20 at 00:22