1

I want to share a structure Foo between several other structures with the ability to extract this data. All other holders of this structure will see the value disappear.

Pseudocode:

if boo.ref_to_foo.is_valid() {
   let foo: Foo = boo.ref_to_foo.steal(); //1
} else {
   //after executing 1 one time all come here 
}

I do not need multithreading.

Is Rc<RefCell<Foo>> what I want? Deref for Rc + RefCell::borrow_mut + Option::take, or maybe some simpler way to achieve what I want?

Shepmaster
  • 388,571
  • 95
  • 1,107
  • 1,366
user1244932
  • 7,352
  • 5
  • 46
  • 103

1 Answers1

4

Is there a shared pointer from which it is possible to steal data?

No, but you have all the building blocks you need to create one. Since you

  • want to change the value, you need the interior mutability provided by RefCell.
  • want to share ownership, you need Rc.
  • want to have the possibility of having a value or not a value, you need Option.
use std::rc::Rc;
use std::cell::RefCell;

struct Foo;

fn main() {
    let foo1 = Rc::new(RefCell::new(Some(Foo)));
    let foo2 = foo1.clone();

    if foo1.borrow().is_some() {
        let stolen = foo1.borrow_mut().take();
    } else {
        println!("Already stolen!")
    }

    if foo2.borrow().is_some() {
        let stolen = foo2.borrow_mut().take();
    } else {
        println!("Already stolen!")
    }
}

If you felt like it, you could probably wrap all this up into a single type.

See also:

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