Struct alloc::rc::Rc

1.0.0 · source · []
pub struct Rc<T: ?Sized> { /* private fields */ }
Expand description

A single-threaded reference-counting pointer. ‘Rc’ stands for ‘Reference Counted’.

See the module-level documentation for more details.

The inherent methods of Rc are all associated functions, which means that you have to call them as e.g., Rc::get_mut(&mut value) instead of value.get_mut(). This avoids conflicts with methods of the inner type T.

Implementations

Constructs a new Rc<T>.

Examples
use std::rc::Rc;

let five = Rc::new(5);
Run

Constructs a new Rc<T> while giving you a Weak<T> to the allocation, to allow you to construct a T which holds a weak pointer to itself.

Generally, a structure circularly referencing itself, either directly or indirectly, should not hold a strong reference to itself to prevent a memory leak. Using this function, you get access to the weak pointer during the initialization of T, before the Rc<T> is created, such that you can clone and store it inside the T.

new_cyclic first allocates the managed allocation for the Rc<T>, then calls your closure, giving it a Weak<T> to this allocation, and only afterwards completes the construction of the Rc<T> by placing the T returned from your closure into the allocation.

Since the new Rc<T> is not fully-constructed until Rc<T>::new_cyclic returns, calling upgrade on the weak reference inside your closure will fail and result in a None value.

Panics

If data_fn panics, the panic is propagated to the caller, and the temporary Weak<T> is dropped normally.

Examples
use std::rc::{Rc, Weak};

struct Gadget {
    me: Weak<Gadget>,
}

impl Gadget {
    /// Construct a reference counted Gadget.
    fn new() -> Rc<Self> {
        // `me` is a `Weak<Gadget>` pointing at the new allocation of the
        // `Rc` we're constructing.
        Rc::new_cyclic(|me| {
            // Create the actual struct here.
            Gadget { me: me.clone() }
        })
    }

    /// Return a reference counted pointer to Self.
    fn me(&self) -> Rc<Self> {
        self.me.upgrade().unwrap()
    }
}
Run
🔬This is a nightly-only experimental API. (new_uninit #63291)

Constructs a new Rc with uninitialized contents.

Examples
#![feature(new_uninit)]
#![feature(get_mut_unchecked)]

use std::rc::Rc;

let mut five = Rc::<u32>::new_uninit();

// Deferred initialization:
Rc::get_mut(&mut five).unwrap().write(5);

let five = unsafe { five.assume_init() };

assert_eq!(*five, 5)
Run
🔬This is a nightly-only experimental API. (new_uninit #63291)

Constructs a new Rc with uninitialized contents, with the memory being filled with 0 bytes.

See MaybeUninit::zeroed for examples of correct and incorrect usage of this method.

Examples
#![feature(new_uninit)]

use std::rc::Rc;

let zero = Rc::<u32>::new_zeroed();
let zero = unsafe { zero.assume_init() };

assert_eq!(*zero, 0)
Run
🔬This is a nightly-only experimental API. (allocator_api #32838)

Constructs a new Rc<T>, returning an error if the allocation fails

Examples
#![feature(allocator_api)]
use std::rc::Rc;

let five = Rc::try_new(5);
Run
🔬This is a nightly-only experimental API. (allocator_api #32838)

Constructs a new Rc with uninitialized contents, returning an error if the allocation fails

Examples
#![feature(allocator_api, new_uninit)]
#![feature(get_mut_unchecked)]

use std::rc::Rc;

let mut five = Rc::<u32>::try_new_uninit()?;

// Deferred initialization:
Rc::get_mut(&mut five).unwrap().write(5);

let five = unsafe { five.assume_init() };

assert_eq!(*five, 5);
Run
🔬This is a nightly-only experimental API. (allocator_api #32838)

Constructs a new Rc with uninitialized contents, with the memory being filled with 0 bytes, returning an error if the allocation fails

See MaybeUninit::zeroed for examples of correct and incorrect usage of this method.

Examples
#![feature(allocator_api, new_uninit)]

use std::rc::Rc;

let zero = Rc::<u32>::try_new_zeroed()?;
let zero = unsafe { zero.assume_init() };

assert_eq!(*zero, 0);
Run

Constructs a new Pin<Rc<T>>. If T does not implement Unpin, then value will be pinned in memory and unable to be moved.

Returns the inner value, if the Rc has exactly one strong reference.

Otherwise, an Err is returned with the same Rc that was passed in.

This will succeed even if there are outstanding weak references.

Examples
use std::rc::Rc;

let x = Rc::new(3);
assert_eq!(Rc::try_unwrap(x), Ok(3));

let x = Rc::new(4);
let _y = Rc::clone(&x);
assert_eq!(*Rc::try_unwrap(x).unwrap_err(), 4);
Run
🔬This is a nightly-only experimental API. (new_uninit #63291)

Constructs a new reference-counted slice with uninitialized contents.

Examples
#![feature(new_uninit)]
#![feature(get_mut_unchecked)]

use std::rc::Rc;

let mut values = Rc::<[u32]>::new_uninit_slice(3);

// Deferred initialization:
let data = Rc::get_mut(&mut values).unwrap();
data[0].write(1);
data[1].write(2);
data[2].write(3);

let values = unsafe { values.assume_init() };

assert_eq!(*values, [1, 2, 3])
Run
🔬This is a nightly-only experimental API. (new_uninit #63291)

Constructs a new reference-counted slice with uninitialized contents, with the memory being filled with 0 bytes.

See MaybeUninit::zeroed for examples of correct and incorrect usage of this method.

Examples
#![feature(new_uninit)]

use std::rc::Rc;

let values = Rc::<[u32]>::new_zeroed_slice(3);
let values = unsafe { values.assume_init() };

assert_eq!(*values, [0, 0, 0])
Run
🔬This is a nightly-only experimental API. (new_uninit #63291)

Converts to Rc<T>.

Safety

As with MaybeUninit::assume_init, it is up to the caller to guarantee that the inner value really is in an initialized state. Calling this when the content is not yet fully initialized causes immediate undefined behavior.

Examples
#![feature(new_uninit)]
#![feature(get_mut_unchecked)]

use std::rc::Rc;

let mut five = Rc::<u32>::new_uninit();

// Deferred initialization:
Rc::get_mut(&mut five).unwrap().write(5);

let five = unsafe { five.assume_init() };

assert_eq!(*five, 5)
Run
🔬This is a nightly-only experimental API. (new_uninit #63291)

Converts to Rc<[T]>.

Safety

As with MaybeUninit::assume_init, it is up to the caller to guarantee that the inner value really is in an initialized state. Calling this when the content is not yet fully initialized causes immediate undefined behavior.

Examples
#![feature(new_uninit)]
#![feature(get_mut_unchecked)]

use std::rc::Rc;

let mut values = Rc::<[u32]>::new_uninit_slice(3);

// Deferred initialization:
let data = Rc::get_mut(&mut values).unwrap();
data[0].write(1);
data[1].write(2);
data[2].write(3);

let values = unsafe { values.assume_init() };

assert_eq!(*values, [1, 2, 3])
Run

Consumes the Rc, returning the wrapped pointer.

To avoid a memory leak the pointer must be converted back to an Rc using Rc::from_raw.

Examples
use std::rc::Rc;

let x = Rc::new("hello".to_owned());
let x_ptr = Rc::into_raw(x);
assert_eq!(unsafe { &*x_ptr }, "hello");
Run

Provides a raw pointer to the data.

The counts are not affected in any way and the Rc is not consumed. The pointer is valid for as long there are strong counts in the Rc.

Examples
use std::rc::Rc;

let x = Rc::new("hello".to_owned());
let y = Rc::clone(&x);
let x_ptr = Rc::as_ptr(&x);
assert_eq!(x_ptr, Rc::as_ptr(&y));
assert_eq!(unsafe { &*x_ptr }, "hello");
Run

Constructs an Rc<T> from a raw pointer.

The raw pointer must have been previously returned by a call to Rc<U>::into_raw where U must have the same size and alignment as T. This is trivially true if U is T. Note that if U is not T but has the same size and alignment, this is basically like transmuting references of different types. See mem::transmute for more information on what restrictions apply in this case.

The user of from_raw has to make sure a specific value of T is only dropped once.

This function is unsafe because improper use may lead to memory unsafety, even if the returned Rc<T> is never accessed.

Examples
use std::rc::Rc;

let x = Rc::new("hello".to_owned());
let x_ptr = Rc::into_raw(x);

unsafe {
    // Convert back to an `Rc` to prevent leak.
    let x = Rc::from_raw(x_ptr);
    assert_eq!(&*x, "hello");

    // Further calls to `Rc::from_raw(x_ptr)` would be memory-unsafe.
}

// The memory was freed when `x` went out of scope above, so `x_ptr` is now dangling!
Run

Creates a new Weak pointer to this allocation.

Examples
use std::rc::Rc;

let five = Rc::new(5);

let weak_five = Rc::downgrade(&five);
Run

Gets the number of Weak pointers to this allocation.

Examples
use std::rc::Rc;

let five = Rc::new(5);
let _weak_five = Rc::downgrade(&five);

assert_eq!(1, Rc::weak_count(&five));
Run

Gets the number of strong (Rc) pointers to this allocation.

Examples
use std::rc::Rc;

let five = Rc::new(5);
let _also_five = Rc::clone(&five);

assert_eq!(2, Rc::strong_count(&five));
Run

Increments the strong reference count on the Rc<T> associated with the provided pointer by one.

Safety

The pointer must have been obtained through Rc::into_raw, and the associated Rc instance must be valid (i.e. the strong count must be at least 1) for the duration of this method.

Examples
use std::rc::Rc;

let five = Rc::new(5);

unsafe {
    let ptr = Rc::into_raw(five);
    Rc::increment_strong_count(ptr);

    let five = Rc::from_raw(ptr);
    assert_eq!(2, Rc::strong_count(&five));
}
Run

Decrements the strong reference count on the Rc<T> associated with the provided pointer by one.

Safety

The pointer must have been obtained through Rc::into_raw, and the associated Rc instance must be valid (i.e. the strong count must be at least 1) when invoking this method. This method can be used to release the final Rc and backing storage, but should not be called after the final Rc has been released.

Examples
use std::rc::Rc;

let five = Rc::new(5);

unsafe {
    let ptr = Rc::into_raw(five);
    Rc::increment_strong_count(ptr);

    let five = Rc::from_raw(ptr);
    assert_eq!(2, Rc::strong_count(&five));
    Rc::decrement_strong_count(ptr);
    assert_eq!(1, Rc::strong_count(&five));
}
Run

Returns a mutable reference into the given Rc, if there are no other Rc or Weak pointers to the same allocation.

Returns None otherwise, because it is not safe to mutate a shared value.

See also make_mut, which will clone the inner value when there are other Rc pointers.

Examples
use std::rc::Rc;

let mut x = Rc::new(3);
*Rc::get_mut(&mut x).unwrap() = 4;
assert_eq!(*x, 4);

let _y = Rc::clone(&x);
assert!(Rc::get_mut(&mut x).is_none());
Run
🔬This is a nightly-only experimental API. (get_mut_unchecked #63292)

Returns a mutable reference into the given Rc, without any check.

See also get_mut, which is safe and does appropriate checks.

Safety

Any other Rc or Weak pointers to the same allocation must not be dereferenced for the duration of the returned borrow. This is trivially the case if no such pointers exist, for example immediately after Rc::new.

Examples
#![feature(get_mut_unchecked)]

use std::rc::Rc;

let mut x = Rc::new(String::new());
unsafe {
    Rc::get_mut_unchecked(&mut x).push_str("foo")
}
assert_eq!(*x, "foo");
Run

Returns true if the two Rcs point to the same allocation (in a vein similar to ptr::eq).

Examples
use std::rc::Rc;

let five = Rc::new(5);
let same_five = Rc::clone(&five);
let other_five = Rc::new(5);

assert!(Rc::ptr_eq(&five, &same_five));
assert!(!Rc::ptr_eq(&five, &other_five));
Run

Makes a mutable reference into the given Rc.

If there are other Rc pointers to the same allocation, then make_mut will clone the inner value to a new allocation to ensure unique ownership. This is also referred to as clone-on-write.

However, if there are no other Rc pointers to this allocation, but some Weak pointers, then the Weak pointers will be disassociated and the inner value will not be cloned.

See also get_mut, which will fail rather than cloning the inner value or disassociating Weak pointers.

Examples
use std::rc::Rc;

let mut data = Rc::new(5);

*Rc::make_mut(&mut data) += 1;         // Won't clone anything
let mut other_data = Rc::clone(&data); // Won't clone inner data
*Rc::make_mut(&mut data) += 1;         // Clones inner data
*Rc::make_mut(&mut data) += 1;         // Won't clone anything
*Rc::make_mut(&mut other_data) *= 2;   // Won't clone anything

// Now `data` and `other_data` point to different allocations.
assert_eq!(*data, 8);
assert_eq!(*other_data, 12);
Run

Weak pointers will be disassociated:

use std::rc::Rc;

let mut data = Rc::new(75);
let weak = Rc::downgrade(&data);

assert!(75 == *data);
assert!(75 == *weak.upgrade().unwrap());

*Rc::make_mut(&mut data) += 1;

assert!(76 == *data);
assert!(weak.upgrade().is_none());
Run
🔬This is a nightly-only experimental API. (arc_unwrap_or_clone #93610)

If we have the only reference to T then unwrap it. Otherwise, clone T and return the clone.

Assuming rc_t is of type Rc<T>, this function is functionally equivalent to (*rc_t).clone(), but will avoid cloning the inner value where possible.

Examples
#![feature(arc_unwrap_or_clone)]
let inner = String::from("test");
let ptr = inner.as_ptr();

let rc = Rc::new(inner);
let inner = Rc::unwrap_or_clone(rc);
// The inner value was not cloned
assert!(ptr::eq(ptr, inner.as_ptr()));

let rc = Rc::new(inner);
let rc2 = rc.clone();
let inner = Rc::unwrap_or_clone(rc);
// Because there were 2 references, we had to clone the inner value.
assert!(!ptr::eq(ptr, inner.as_ptr()));
// `rc2` is the last reference, so when we unwrap it we get back
// the original `String`.
let inner = Rc::unwrap_or_clone(rc2);
assert!(ptr::eq(ptr, inner.as_ptr()));
Run

Attempt to downcast the Rc<dyn Any> to a concrete type.

Examples
use std::any::Any;
use std::rc::Rc;

fn print_if_string(value: Rc<dyn Any>) {
    if let Ok(string) = value.downcast::<String>() {
        println!("String ({}): {}", string.len(), string);
    }
}

let my_string = "Hello World".to_string();
print_if_string(Rc::new(my_string));
print_if_string(Rc::new(0i8));
Run
🔬This is a nightly-only experimental API. (downcast_unchecked #90850)

Downcasts the Rc<dyn Any> to a concrete type.

For a safe alternative see downcast.

Examples
#![feature(downcast_unchecked)]

use std::any::Any;
use std::rc::Rc;

let x: Rc<dyn Any> = Rc::new(1_usize);

unsafe {
    assert_eq!(*x.downcast_unchecked::<usize>(), 1);
}
Run
Safety

The contained value must be of type T. Calling this method with the incorrect type is undefined behavior.

Trait Implementations

Converts this type into a shared reference of the (usually inferred) input type.
Immutably borrows from an owned value. Read more

Makes a clone of the Rc pointer.

This creates another pointer to the same allocation, increasing the strong reference count.

Examples
use std::rc::Rc;

let five = Rc::new(5);

let _ = Rc::clone(&five);
Run
Performs copy-assignment from source. Read more
Formats the value using the given formatter. Read more

Creates a new Rc<T>, with the Default value for T.

Examples
use std::rc::Rc;

let x: Rc<i32> = Default::default();
assert_eq!(*x, 0);
Run
The resulting type after dereferencing.
Dereferences the value.
Formats the value using the given formatter. Read more

Drops the Rc.

This will decrement the strong reference count. If the strong reference count reaches zero then the only other references (if any) are Weak, so we drop the inner value.

Examples
use std::rc::Rc;

struct Foo;

impl Drop for Foo {
    fn drop(&mut self) {
        println!("dropped!");
    }
}

let foo  = Rc::new(Foo);
let foo2 = Rc::clone(&foo);

drop(foo);    // Doesn't print anything
drop(foo2);   // Prints "dropped!"
Run

Allocate a reference-counted slice and fill it by cloning v’s items.

Example
let original: &[i32] = &[1, 2, 3];
let shared: Rc<[i32]> = Rc::from(original);
assert_eq!(&[1, 2, 3], &shared[..]);
Run

Converts a &CStr into a Rc<CStr>, by copying the contents into a newly allocated Rc.

Allocate a reference-counted string slice and copy v into it.

Example
let shared: Rc<str> = Rc::from("statue");
assert_eq!("statue", &shared[..]);
Run

Move a boxed object to a new, reference counted, allocation.

Example
let original: Box<i32> = Box::new(1);
let shared: Rc<i32> = Rc::from(original);
assert_eq!(1, *shared);
Run

Converts a CString into an Rc<CStr> by moving the CString data into a new Arc buffer.

Create a reference-counted pointer from a clone-on-write pointer by copying its content.

Example
let cow: Cow<str> = Cow::Borrowed("eggplant");
let shared: Rc<str> = Rc::from(cow);
assert_eq!("eggplant", &shared[..]);
Run

Converts a reference-counted string slice into a byte slice.

Example
let string: Rc<str> = Rc::from("eggplant");
let bytes: Rc<[u8]> = Rc::from(string);
assert_eq!("eggplant".as_bytes(), bytes.as_ref());
Run

Allocate a reference-counted string slice and copy v into it.

Example
let original: String = "statue".to_owned();
let shared: Rc<str> = Rc::from(original);
assert_eq!("statue", &shared[..]);
Run

Converts a generic type T into an Rc<T>

The conversion allocates on the heap and moves t from the stack into it.

Example
let x = 5;
let rc = Rc::new(5);

assert_eq!(Rc::from(x), rc);
Run

Allocate a reference-counted slice and move v’s items into it.

Example
let original: Box<Vec<i32>> = Box::new(vec![1, 2, 3]);
let shared: Rc<Vec<i32>> = Rc::from(original);
assert_eq!(vec![1, 2, 3], *shared);
Run

Takes each element in the Iterator and collects it into an Rc<[T]>.

Performance characteristics
The general case

In the general case, collecting into Rc<[T]> is done by first collecting into a Vec<T>. That is, when writing the following:

let evens: Rc<[u8]> = (0..10).filter(|&x| x % 2 == 0).collect();
Run

this behaves as if we wrote:

let evens: Rc<[u8]> = (0..10).filter(|&x| x % 2 == 0)
    .collect::<Vec<_>>() // The first set of allocations happens here.
    .into(); // A second allocation for `Rc<[T]>` happens here.
Run

This will allocate as many times as needed for constructing the Vec<T> and then it will allocate once for turning the Vec<T> into the Rc<[T]>.

Iterators of known length

When your Iterator implements TrustedLen and is of an exact size, a single allocation will be made for the Rc<[T]>. For example:

let evens: Rc<[u8]> = (0..10).collect(); // Just a single allocation happens here.
Run
Feeds this value into the given Hasher. Read more
Feeds a slice of this type into the given Hasher. Read more

Comparison for two Rcs.

The two are compared by calling cmp() on their inner values.

Examples
use std::rc::Rc;
use std::cmp::Ordering;

let five = Rc::new(5);

assert_eq!(Ordering::Less, five.cmp(&Rc::new(6)));
Run
Compares and returns the maximum of two values. Read more
Compares and returns the minimum of two values. Read more
Restrict a value to a certain interval. Read more

Equality for two Rcs.

Two Rcs are equal if their inner values are equal, even if they are stored in different allocation.

If T also implements Eq (implying reflexivity of equality), two Rcs that point to the same allocation are always equal.

Examples
use std::rc::Rc;

let five = Rc::new(5);

assert!(five == Rc::new(5));
Run

Inequality for two Rcs.

Two Rcs are unequal if their inner values are unequal.

If T also implements Eq (implying reflexivity of equality), two Rcs that point to the same allocation are never unequal.

Examples
use std::rc::Rc;

let five = Rc::new(5);

assert!(five != Rc::new(6));
Run

Partial comparison for two Rcs.

The two are compared by calling partial_cmp() on their inner values.

Examples
use std::rc::Rc;
use std::cmp::Ordering;

let five = Rc::new(5);

assert_eq!(Some(Ordering::Less), five.partial_cmp(&Rc::new(6)));
Run

Less-than comparison for two Rcs.

The two are compared by calling < on their inner values.

Examples
use std::rc::Rc;

let five = Rc::new(5);

assert!(five < Rc::new(6));
Run

‘Less than or equal to’ comparison for two Rcs.

The two are compared by calling <= on their inner values.

Examples
use std::rc::Rc;

let five = Rc::new(5);

assert!(five <= Rc::new(5));
Run

Greater-than comparison for two Rcs.

The two are compared by calling > on their inner values.

Examples
use std::rc::Rc;

let five = Rc::new(5);

assert!(five > Rc::new(4));
Run

‘Greater than or equal to’ comparison for two Rcs.

The two are compared by calling >= on their inner values.

Examples
use std::rc::Rc;

let five = Rc::new(5);

assert!(five >= Rc::new(5));
Run
Formats the value using the given formatter.
The type returned in the event of a conversion error.
Performs the conversion.

Blanket Implementations

Gets the TypeId of self. Read more
Immutably borrows from an owned value. Read more
Mutably borrows from an owned value. Read more
Converts to this type from the input type.

Returns the argument unchanged.

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

The resulting type after obtaining ownership.
Creates owned data from borrowed data, usually by cloning. Read more
Uses borrowed data to replace owned data, usually by cloning. Read more
Converts the given value to a String. Read more
The type returned in the event of a conversion error.
Performs the conversion.
The type returned in the event of a conversion error.
Performs the conversion.