Using into_inner for moving out of an Rc

Playground: Rust Playground

I'm revising some code that uses UnsafeCell.

I have to share access to Foo for a while, but eventually, it needs to be taken from the Rc. I thought that was what .into_inner did. But apparently not. .into _inner wants to copy. I want to consume the Rc and return ownership of the RefCell inside. Is there some way to do that?

You want to use Rc::into_inner, which is an associated function on Rc, not a method:

#![allow(dead_code)]

use std::cell::RefCell;
use std::rc::Rc;

/// Non-cloneable, non-copyable Foo
#[derive(Debug)]
struct Foo {
    n: u32,
}

fn main() {
    //  Rc<RefCell<Foo>> for interior mutability
    let rcitem = Rc::new(RefCell::new(Foo { n: 100 }));
    let inner = Rc::into_inner(rcitem).unwrap();
    println!("Inner: {:?}", inner);
}

Playground.

Method call resolution on types that implement Deref perform deref coercion[1] in order to find the correct receiver type. This means you end up calling RefCell::into_inner in your example, which'd move the data out of a shared reference to the RefCell (that you get from <Rc as Deref>::deref implicitly added as part of the aforementioned method call resolution), which is not allowed.


  1. Edit: I don't think deref coercion is the correct term to use here, it's more that &<Rc as Deref>::Target is added to the list of possible method call receivers. ↩ī¸Ž

3 Likes

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.