pub struct Rc<T, A =Global>{/* private fields */ }Expand description
A single-threaded reference-counting pointer. ‘Rc’ stands for ‘ReferenceCounted’.
See themodule-level documentation for more details.
The inherent methods ofRc are all associated functions, which meansthat you have to call them as e.g.,Rc::get_mut(&mut value) instead ofvalue.get_mut(). This avoids conflicts with methods of the inner typeT.
Implementations§
Source§impl<T>Rc<T>
impl<T>Rc<T>
1.60.0 ·Sourcepub fnnew_cyclic<F>(data_fn: F) ->Rc<T>
pub fnnew_cyclic<F>(data_fn: F) ->Rc<T>
Constructs a newRc<T> while giving you aWeak<T> to the allocation,to allow you to construct aT which holds a weak pointer to itself.
Generally, a structure circularly referencing itself, either directly orindirectly, should not hold a strong reference to itself to prevent a memory leak.Using this function, you get access to the weak pointer during theinitialization ofT, before theRc<T> is created, such that you canclone and store it inside theT.
new_cyclic first allocates the managed allocation for theRc<T>,then calls your closure, giving it aWeak<T> to this allocation,and only afterwards completes the construction of theRc<T> by placingtheT returned from your closure into the allocation.
Since the newRc<T> is not fully-constructed untilRc<T>::new_cyclicreturns, callingupgrade on the weak reference inside your closure willfail and result in aNone value.
§Panics
Ifdata_fn panics, the panic is propagated to the caller, and thetemporaryWeak<T> is dropped normally.
§Examples
usestd::rc::{Rc, Weak};structGadget { me: Weak<Gadget>,}implGadget {/// Constructs a reference counted Gadget.fnnew() -> 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() } }) }/// Returns a reference counted pointer to Self.fnme(&self) -> Rc<Self> {self.me.upgrade().unwrap() }}1.82.0 ·Sourcepub fnnew_uninit() ->Rc<MaybeUninit<T>>
pub fnnew_uninit() ->Rc<MaybeUninit<T>>
Constructs a newRc with uninitialized contents.
§Examples
1.92.0 ·Sourcepub fnnew_zeroed() ->Rc<MaybeUninit<T>>
pub fnnew_zeroed() ->Rc<MaybeUninit<T>>
Constructs a newRc with uninitialized contents, with the memorybeing filled with0 bytes.
SeeMaybeUninit::zeroed for examples of correct andincorrect usage of this method.
§Examples
Sourcepub fntry_new(value: T) ->Result<Rc<T>,AllocError>
🔬This is a nightly-only experimental API. (allocator_api #32838)
pub fntry_new(value: T) ->Result<Rc<T>,AllocError>
allocator_api #32838)Constructs a newRc<T>, returning an error if the allocation fails
§Examples
Sourcepub fntry_new_uninit() ->Result<Rc<MaybeUninit<T>>,AllocError>
🔬This is a nightly-only experimental API. (allocator_api #32838)
pub fntry_new_uninit() ->Result<Rc<MaybeUninit<T>>,AllocError>
allocator_api #32838)Constructs a newRc with uninitialized contents, returning an error if the allocation fails
§Examples
Sourcepub fntry_new_zeroed() ->Result<Rc<MaybeUninit<T>>,AllocError>
🔬This is a nightly-only experimental API. (allocator_api #32838)
pub fntry_new_zeroed() ->Result<Rc<MaybeUninit<T>>,AllocError>
allocator_api #32838)Constructs a newRc with uninitialized contents, with the memorybeing filled with0 bytes, returning an error if the allocation fails
SeeMaybeUninit::zeroed for examples of correct andincorrect usage of this method.
§Examples
1.33.0 ·Sourcepub fnpin(value: T) ->Pin<Rc<T>>
pub fnpin(value: T) ->Pin<Rc<T>>
Constructs a newPin<Rc<T>>. IfT does not implementUnpin, thenvalue will be pinned in memory and unable to be moved.
Sourcepub fnmap<U>(this:Rc<T>, f: implFnOnce(&T) -> U) ->Rc<U>
🔬This is a nightly-only experimental API. (smart_pointer_try_map #144419)
pub fnmap<U>(this:Rc<T>, f: implFnOnce(&T) -> U) ->Rc<U>
smart_pointer_try_map #144419)Maps the value in anRc, reusing the allocation if possible.
f is called on a reference to the value in theRc, and the result is returned, also inanRc.
Note: this is an associated function, which means that you haveto call it asRc::map(r, f) instead ofr.map(f). Thisis so that there is no conflict with a method on the inner type.
§Examples
Sourcepub fntry_map<R>( this:Rc<T>, f: implFnOnce(&T) -> R,) -> <<R asTry>::Residual asResidual<Rc<<R asTry>::Output>>>::TryType
🔬This is a nightly-only experimental API. (smart_pointer_try_map #144419)
pub fntry_map<R>( this:Rc<T>, f: implFnOnce(&T) -> R,) -> <<R asTry>::Residual asResidual<Rc<<R asTry>::Output>>>::TryType
smart_pointer_try_map #144419)Attempts to map the value in anRc, reusing the allocation if possible.
f is called on a reference to the value in theRc, and if the operation succeeds, theresult is returned, also in anRc.
Note: this is an associated function, which means that you haveto call it asRc::try_map(r, f) instead ofr.try_map(f). Thisis so that there is no conflict with a method on the inner type.
§Examples
Source§impl<T, A>Rc<T, A>where A:Allocator,
impl<T, A>Rc<T, A>where A:Allocator,
Sourcepub fnnew_in(value: T, alloc: A) ->Rc<T, A>
🔬This is a nightly-only experimental API. (allocator_api #32838)
pub fnnew_in(value: T, alloc: A) ->Rc<T, A>
allocator_api #32838)Constructs a newRc in the provided allocator.
§Examples
Sourcepub fnnew_uninit_in(alloc: A) ->Rc<MaybeUninit<T>, A>
🔬This is a nightly-only experimental API. (allocator_api #32838)
pub fnnew_uninit_in(alloc: A) ->Rc<MaybeUninit<T>, A>
allocator_api #32838)Constructs a newRc with uninitialized contents in the provided allocator.
§Examples
Sourcepub fnnew_zeroed_in(alloc: A) ->Rc<MaybeUninit<T>, A>
🔬This is a nightly-only experimental API. (allocator_api #32838)
pub fnnew_zeroed_in(alloc: A) ->Rc<MaybeUninit<T>, A>
allocator_api #32838)Constructs a newRc with uninitialized contents, with the memorybeing filled with0 bytes, in the provided allocator.
SeeMaybeUninit::zeroed for examples of correct andincorrect usage of this method.
§Examples
Sourcepub fnnew_cyclic_in<F>(data_fn: F, alloc: A) ->Rc<T, A>
🔬This is a nightly-only experimental API. (allocator_api #32838)
pub fnnew_cyclic_in<F>(data_fn: F, alloc: A) ->Rc<T, A>
allocator_api #32838)Constructs a newRc<T, A> in the given allocator while giving you aWeak<T, A> to the allocation,to allow you to construct aT which holds a weak pointer to itself.
Generally, a structure circularly referencing itself, either directly orindirectly, should not hold a strong reference to itself to prevent a memory leak.Using this function, you get access to the weak pointer during theinitialization ofT, before theRc<T, A> is created, such that you canclone and store it inside theT.
new_cyclic_in first allocates the managed allocation for theRc<T, A>,then calls your closure, giving it aWeak<T, A> to this allocation,and only afterwards completes the construction of theRc<T, A> by placingtheT returned from your closure into the allocation.
Since the newRc<T, A> is not fully-constructed untilRc<T, A>::new_cyclic_inreturns, callingupgrade on the weak reference inside your closure willfail and result in aNone value.
§Panics
Ifdata_fn panics, the panic is propagated to the caller, and thetemporaryWeak<T, A> is dropped normally.
§Examples
Seenew_cyclic.
Sourcepub fntry_new_in(value: T, alloc: A) ->Result<Rc<T, A>,AllocError>
🔬This is a nightly-only experimental API. (allocator_api #32838)
pub fntry_new_in(value: T, alloc: A) ->Result<Rc<T, A>,AllocError>
allocator_api #32838)Constructs a newRc<T> in the provided allocator, returning an error if the allocationfails
§Examples
Sourcepub fntry_new_uninit_in(alloc: A) ->Result<Rc<MaybeUninit<T>, A>,AllocError>
🔬This is a nightly-only experimental API. (allocator_api #32838)
pub fntry_new_uninit_in(alloc: A) ->Result<Rc<MaybeUninit<T>, A>,AllocError>
allocator_api #32838)Constructs a newRc with uninitialized contents, in the provided allocator, returning anerror if the allocation fails
§Examples
Sourcepub fntry_new_zeroed_in(alloc: A) ->Result<Rc<MaybeUninit<T>, A>,AllocError>
🔬This is a nightly-only experimental API. (allocator_api #32838)
pub fntry_new_zeroed_in(alloc: A) ->Result<Rc<MaybeUninit<T>, A>,AllocError>
allocator_api #32838)Constructs a newRc with uninitialized contents, with the memorybeing filled with0 bytes, in the provided allocator, returning an error if the allocationfails
SeeMaybeUninit::zeroed for examples of correct andincorrect usage of this method.
§Examples
Sourcepub fnpin_in(value: T, alloc: A) ->Pin<Rc<T, A>>where A: 'static,
🔬This is a nightly-only experimental API. (allocator_api #32838)
pub fnpin_in(value: T, alloc: A) ->Pin<Rc<T, A>>where A: 'static,
allocator_api #32838)Constructs a newPin<Rc<T>> in the provided allocator. IfT does not implementUnpin, thenvalue will be pinned in memory and unable to be moved.
1.4.0 ·Sourcepub fntry_unwrap(this:Rc<T, A>) ->Result<T,Rc<T, A>>
pub fntry_unwrap(this:Rc<T, A>) ->Result<T,Rc<T, A>>
1.70.0 ·Sourcepub fninto_inner(this:Rc<T, A>) ->Option<T>
pub fninto_inner(this:Rc<T, A>) ->Option<T>
Returns the inner value, if theRc has exactly one strong reference.
Otherwise,None is returned and theRc is dropped.
This will succeed even if there are outstanding weak references.
IfRc::into_inner is called on every clone of thisRc,it is guaranteed that exactly one of the calls returns the inner value.This means in particular that the inner value is not dropped.
Rc::try_unwrap is conceptually similar toRc::into_inner.And while they are meant for different use-cases,Rc::into_inner(this)is in fact equivalent toRc::try_unwrap(this).ok().(Note that the same kind of equivalence doesnot hold true forArc, due to race conditions that do not apply toRc!)
§Examples
Source§impl<T>Rc<[T]>
impl<T>Rc<[T]>
1.82.0 ·Sourcepub fnnew_uninit_slice(len:usize) ->Rc<[MaybeUninit<T>]>
pub fnnew_uninit_slice(len:usize) ->Rc<[MaybeUninit<T>]>
Constructs a new reference-counted slice with uninitialized contents.
§Examples
1.92.0 ·Sourcepub fnnew_zeroed_slice(len:usize) ->Rc<[MaybeUninit<T>]>
pub fnnew_zeroed_slice(len:usize) ->Rc<[MaybeUninit<T>]>
Constructs a new reference-counted slice with uninitialized contents, with the memory beingfilled with0 bytes.
SeeMaybeUninit::zeroed for examples of correct andincorrect usage of this method.
§Examples
Sourcepub fninto_array<const N:usize>(self) ->Option<Rc<[T; N]>>
🔬This is a nightly-only experimental API. (alloc_slice_into_array #148082)
pub fninto_array<const N:usize>(self) ->Option<Rc<[T; N]>>
alloc_slice_into_array #148082)Converts the reference-counted slice into a reference-counted array.
This operation does not reallocate; the underlying array of the slice is simply reinterpreted as an array type.
IfN is not exactly equal to the length ofself, then this method returnsNone.
Source§impl<T, A>Rc<[T], A>where A:Allocator,
impl<T, A>Rc<[T], A>where A:Allocator,
Sourcepub fnnew_uninit_slice_in(len:usize, alloc: A) ->Rc<[MaybeUninit<T>], A>
🔬This is a nightly-only experimental API. (allocator_api #32838)
pub fnnew_uninit_slice_in(len:usize, alloc: A) ->Rc<[MaybeUninit<T>], A>
allocator_api #32838)Constructs a new reference-counted slice with uninitialized contents.
§Examples
#![feature(get_mut_unchecked)]#![feature(allocator_api)]usestd::rc::Rc;usestd::alloc::System;letmutvalues = Rc::<[u32],_>::new_uninit_slice_in(3, System);letvalues =unsafe{// Deferred initialization:Rc::get_mut_unchecked(&mutvalues)[0].as_mut_ptr().write(1); Rc::get_mut_unchecked(&mutvalues)[1].as_mut_ptr().write(2); Rc::get_mut_unchecked(&mutvalues)[2].as_mut_ptr().write(3); values.assume_init()};assert_eq!(*values, [1,2,3])Sourcepub fnnew_zeroed_slice_in(len:usize, alloc: A) ->Rc<[MaybeUninit<T>], A>
🔬This is a nightly-only experimental API. (allocator_api #32838)
pub fnnew_zeroed_slice_in(len:usize, alloc: A) ->Rc<[MaybeUninit<T>], A>
allocator_api #32838)Constructs a new reference-counted slice with uninitialized contents, with the memory beingfilled with0 bytes.
SeeMaybeUninit::zeroed for examples of correct andincorrect usage of this method.
§Examples
Source§impl<T, A>Rc<MaybeUninit<T>, A>where A:Allocator,
impl<T, A>Rc<MaybeUninit<T>, A>where A:Allocator,
1.82.0 ·Sourcepub unsafe fnassume_init(self) ->Rc<T, A>
pub unsafe fnassume_init(self) ->Rc<T, A>
Converts toRc<T>.
§Safety
As withMaybeUninit::assume_init,it is up to the caller to guarantee that the inner valuereally is in an initialized state.Calling this when the content is not yet fully initializedcauses immediate undefined behavior.
§Examples
Source§impl<T>Rc<T>where T:CloneToUninit + ?Sized,
impl<T>Rc<T>where T:CloneToUninit + ?Sized,
Sourcepub fnclone_from_ref(value:&T) ->Rc<T>
🔬This is a nightly-only experimental API. (clone_from_ref #149075)
pub fnclone_from_ref(value:&T) ->Rc<T>
clone_from_ref #149075)Constructs a newRc<T> with a clone ofvalue.
§Examples
Sourcepub fntry_clone_from_ref(value:&T) ->Result<Rc<T>,AllocError>
🔬This is a nightly-only experimental API. (clone_from_ref #149075)
pub fntry_clone_from_ref(value:&T) ->Result<Rc<T>,AllocError>
clone_from_ref #149075)Constructs a newRc<T> with a clone ofvalue, returning an error if allocation fails
§Examples
Source§impl<T, A>Rc<T, A>
impl<T, A>Rc<T, A>
Sourcepub fnclone_from_ref_in(value:&T, alloc: A) ->Rc<T, A>
🔬This is a nightly-only experimental API. (clone_from_ref #149075)
pub fnclone_from_ref_in(value:&T, alloc: A) ->Rc<T, A>
clone_from_ref #149075)Constructs a newRc<T> with a clone ofvalue in the provided allocator.
§Examples
Sourcepub fntry_clone_from_ref_in( value:&T, alloc: A,) ->Result<Rc<T, A>,AllocError>
🔬This is a nightly-only experimental API. (clone_from_ref #149075)
pub fntry_clone_from_ref_in( value:&T, alloc: A,) ->Result<Rc<T, A>,AllocError>
clone_from_ref #149075)Constructs a newRc<T> with a clone ofvalue in the provided allocator, returning an error if allocation fails
§Examples
Source§impl<T, A>Rc<[MaybeUninit<T>], A>where A:Allocator,
impl<T, A>Rc<[MaybeUninit<T>], A>where A:Allocator,
1.82.0 ·Sourcepub unsafe fnassume_init(self) ->Rc<[T], A>
pub unsafe fnassume_init(self) ->Rc<[T], A>
Converts toRc<[T]>.
§Safety
As withMaybeUninit::assume_init,it is up to the caller to guarantee that the inner valuereally is in an initialized state.Calling this when the content is not yet fully initializedcauses immediate undefined behavior.
§Examples
Source§impl<T>Rc<T>where T: ?Sized,
impl<T>Rc<T>where T: ?Sized,
1.17.0 ·Sourcepub unsafe fnfrom_raw(ptr:*const T) ->Rc<T>
pub unsafe fnfrom_raw(ptr:*const T) ->Rc<T>
Constructs anRc<T> from a raw pointer.
The raw pointer must have been previously returned by a call toRc<U>::into_raw with the following requirements:
- If
Uis sized, it must have the same size and alignment asT. Thisis trivially true ifUisT. - If
Uis unsized, its data pointer must have the same size andalignment asT. This is trivially true ifRc<U>was constructedthroughRc<T>and then converted toRc<U>through anunsizedcoercion.
Note that ifU orU’s data pointer is notT but has the same sizeand alignment, this is basically like transmuting references ofdifferent types. Seemem::transmute for more informationon what restrictions apply in this case.
The raw pointer must point to a block of memory allocated by the global allocator
The user offrom_raw has to make sure a specific value ofT is onlydropped once.
This function is unsafe because improper use may lead to memory unsafety,even if the returnedRc<T> is never accessed.
§Examples
usestd::rc::Rc;letx = Rc::new("hello".to_owned());letx_ptr = Rc::into_raw(x);unsafe{// Convert back to an `Rc` to prevent leak.letx = 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!Convert a slice back into its original array:
1.17.0 ·Sourcepub fninto_raw(this:Rc<T>) ->*const T
pub fninto_raw(this:Rc<T>) ->*const T
Consumes theRc, returning the wrapped pointer.
To avoid a memory leak the pointer must be converted back to anRc usingRc::from_raw.
§Examples
1.53.0 ·Sourcepub unsafe fnincrement_strong_count(ptr:*const T)
pub unsafe fnincrement_strong_count(ptr:*const T)
Increments the strong reference count on theRc<T> associated with theprovided pointer by one.
§Safety
The pointer must have been obtained throughRc::into_raw and must satisfy thesame layout requirements specified inRc::from_raw_in.The associatedRc instance must be valid (i.e. the strong count must be atleast 1) for the duration of this method, andptr must point to a block of memoryallocated by the global allocator.
§Examples
1.53.0 ·Sourcepub unsafe fndecrement_strong_count(ptr:*const T)
pub unsafe fndecrement_strong_count(ptr:*const T)
Decrements the strong reference count on theRc<T> associated with theprovided pointer by one.
§Safety
The pointer must have been obtained throughRc::into_rawand must satisfy thesame layout requirements specified inRc::from_raw_in.The associatedRc instance must be valid (i.e. the strong count must be atleast 1) when invoking this method, andptr must point to a block of memoryallocated by the global allocator. This method can be used to release the finalRc andbacking storage, butshould not be called after the finalRc has been released.
§Examples
Source§impl<T, A>Rc<T, A>
impl<T, A>Rc<T, A>
Sourcepub fnallocator(this: &Rc<T, A>) ->&A
🔬This is a nightly-only experimental API. (allocator_api #32838)
pub fnallocator(this: &Rc<T, A>) ->&A
allocator_api #32838)Returns a reference to the underlying allocator.
Note: this is an associated function, which means that you haveto call it asRc::allocator(&r) instead ofr.allocator(). Thisis so that there is no conflict with a method on the inner type.
Sourcepub fninto_raw_with_allocator(this:Rc<T, A>) -> (*const T, A)
🔬This is a nightly-only experimental API. (allocator_api #32838)
pub fninto_raw_with_allocator(this:Rc<T, A>) -> (*const T, A)
allocator_api #32838)Consumes theRc, returning the wrapped pointer and allocator.
To avoid a memory leak the pointer must be converted back to anRc usingRc::from_raw_in.
§Examples
1.45.0 ·Sourcepub fnas_ptr(this: &Rc<T, A>) ->*const T
pub fnas_ptr(this: &Rc<T, A>) ->*const T
Provides a raw pointer to the data.
The counts are not affected in any way and theRc is not consumed. The pointer is validfor as long as there are strong counts in theRc.
§Examples
Sourcepub unsafe fnfrom_raw_in(ptr:*const T, alloc: A) ->Rc<T, A>
🔬This is a nightly-only experimental API. (allocator_api #32838)
pub unsafe fnfrom_raw_in(ptr:*const T, alloc: A) ->Rc<T, A>
allocator_api #32838)Constructs anRc<T, A> from a raw pointer in the provided allocator.
The raw pointer must have been previously returned by a call toRc<U, A>::into_raw with the following requirements:
- If
Uis sized, it must have the same size and alignment asT. Thisis trivially true ifUisT. - If
Uis unsized, its data pointer must have the same size andalignment asT. This is trivially true ifRc<U>was constructedthroughRc<T>and then converted toRc<U>through anunsizedcoercion.
Note that ifU orU’s data pointer is notT but has the same sizeand alignment, this is basically like transmuting references ofdifferent types. Seemem::transmute for more informationon what restrictions apply in this case.
The raw pointer must point to a block of memory allocated byalloc
The user offrom_raw has to make sure a specific value ofT is onlydropped once.
This function is unsafe because improper use may lead to memory unsafety,even if the returnedRc<T> is never accessed.
§Examples
#![feature(allocator_api)]usestd::rc::Rc;usestd::alloc::System;letx = Rc::new_in("hello".to_owned(), System);let(x_ptr, _alloc) = Rc::into_raw_with_allocator(x);unsafe{// Convert back to an `Rc` to prevent leak.letx = Rc::from_raw_in(x_ptr, System);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!Convert a slice back into its original array:
1.15.0 ·Sourcepub fnweak_count(this: &Rc<T, A>) ->usize
pub fnweak_count(this: &Rc<T, A>) ->usize
1.15.0 ·Sourcepub fnstrong_count(this: &Rc<T, A>) ->usize
pub fnstrong_count(this: &Rc<T, A>) ->usize
Gets the number of strong (Rc) pointers to this allocation.
§Examples
Sourcepub unsafe fnincrement_strong_count_in(ptr:*const T, alloc: A)where A:Clone,
🔬This is a nightly-only experimental API. (allocator_api #32838)
pub unsafe fnincrement_strong_count_in(ptr:*const T, alloc: A)where A:Clone,
allocator_api #32838)Increments the strong reference count on theRc<T> associated with theprovided pointer by one.
§Safety
The pointer must have been obtained throughRc::into_raw and must satisfy thesame layout requirements specified inRc::from_raw_in.The associatedRc instance must be valid (i.e. the strong count must be atleast 1) for the duration of this method, andptr must point to a block of memoryallocated byalloc.
§Examples
Sourcepub unsafe fndecrement_strong_count_in(ptr:*const T, alloc: A)
🔬This is a nightly-only experimental API. (allocator_api #32838)
pub unsafe fndecrement_strong_count_in(ptr:*const T, alloc: A)
allocator_api #32838)Decrements the strong reference count on theRc<T> associated with theprovided pointer by one.
§Safety
The pointer must have been obtained throughRc::into_rawand must satisfy thesame layout requirements specified inRc::from_raw_in.The associatedRc instance must be valid (i.e. the strong count must be atleast 1) when invoking this method, andptr must point to a block of memoryallocated byalloc. This method can be used to release the finalRc andbacking storage, butshould not be called after the finalRc has been released.
§Examples
#![feature(allocator_api)]usestd::rc::Rc;usestd::alloc::System;letfive = Rc::new_in(5, System);unsafe{let(ptr, _alloc) = Rc::into_raw_with_allocator(five); Rc::increment_strong_count_in(ptr, System);letfive = Rc::from_raw_in(ptr, System);assert_eq!(2, Rc::strong_count(&five)); Rc::decrement_strong_count_in(ptr, System);assert_eq!(1, Rc::strong_count(&five));}1.4.0 ·Sourcepub fnget_mut(this: &mutRc<T, A>) ->Option<&mut T>
pub fnget_mut(this: &mutRc<T, A>) ->Option<&mut T>
Sourcepub unsafe fnget_mut_unchecked(this: &mutRc<T, A>) ->&mut T
🔬This is a nightly-only experimental API. (get_mut_unchecked #63292)
pub unsafe fnget_mut_unchecked(this: &mutRc<T, A>) ->&mut T
get_mut_unchecked #63292)Returns a mutable reference into the givenRc,without any check.
See alsoget_mut, which is safe and does appropriate checks.
§Safety
If any otherRc orWeak pointers to the same allocation exist, thenthey must not be dereferenced or have active borrows for the durationof the returned borrow, and their inner type must be exactly the same as theinner type of this Rc (including lifetimes). This is trivially the case if nosuch pointers exist, for example immediately afterRc::new.
§Examples
#![feature(get_mut_unchecked)]usestd::rc::Rc;letmutx = Rc::new(String::new());unsafe{ Rc::get_mut_unchecked(&mutx).push_str("foo")}assert_eq!(*x,"foo");OtherRc pointers to the same allocation must be to the same type.
#![feature(get_mut_unchecked)]usestd::rc::Rc;letx: Rc<str> = Rc::from("Hello, world!");letmuty: Rc<[u8]> = x.clone().into();unsafe{// this is Undefined Behavior, because x's inner type is str, not [u8]Rc::get_mut_unchecked(&muty).fill(0xff);// 0xff is invalid in UTF-8}println!("{}",&*x);// Invalid UTF-8 in a strOtherRc pointers to the same allocation must be to the exact same type, including lifetimes.
#![feature(get_mut_unchecked)]usestd::rc::Rc;letx: Rc<&str> = Rc::new("Hello, world!");{lets = String::from("Oh, no!");letmuty: Rc<&str> = x.clone();unsafe{// this is Undefined Behavior, because x's inner type // is &'long str, not &'short str*Rc::get_mut_unchecked(&muty) =&s; }}println!("{}",&*x);// Use-after-freeSource§impl<T, A>Rc<T, A>
impl<T, A>Rc<T, A>
1.4.0 ·Sourcepub fnmake_mut(this: &mutRc<T, A>) ->&mut T
pub fnmake_mut(this: &mutRc<T, A>) ->&mut T
Makes a mutable reference into the givenRc.
If there are otherRc pointers to the same allocation, thenmake_mut willclone the inner value to a new allocation to ensure unique ownership. This is alsoreferred to as clone-on-write.
However, if there are no otherRc pointers to this allocation, but someWeakpointers, then theWeak pointers will be disassociated and the inner value will notbe cloned.
See alsoget_mut, which will fail rather than cloning the inner valueor disassociatingWeak pointers.
§Examples
usestd::rc::Rc;letmutdata = Rc::new(5);*Rc::make_mut(&mutdata) +=1;// Won't clone anythingletmutother_data = Rc::clone(&data);// Won't clone inner data*Rc::make_mut(&mutdata) +=1;// Clones inner data*Rc::make_mut(&mutdata) +=1;// Won't clone anything*Rc::make_mut(&mutother_data)*=2;// Won't clone anything// Now `data` and `other_data` point to different allocations.assert_eq!(*data,8);assert_eq!(*other_data,12);Weak pointers will be disassociated:
Source§impl<T, A>Rc<T, A>
impl<T, A>Rc<T, A>
1.76.0 ·Sourcepub fnunwrap_or_clone(this:Rc<T, A>) -> T
pub fnunwrap_or_clone(this:Rc<T, A>) -> T
If we have the only reference toT then unwrap it. Otherwise, cloneT and return theclone.
Assumingrc_t is of typeRc<T>, this function is functionally equivalent to(*rc_t).clone(), but will avoid cloning the inner value where possible.
§Examples
letinner = String::from("test");letptr = inner.as_ptr();letrc = Rc::new(inner);letinner = Rc::unwrap_or_clone(rc);// The inner value was not clonedassert!(ptr::eq(ptr, inner.as_ptr()));letrc = Rc::new(inner);letrc2 = rc.clone();letinner = 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`.letinner = Rc::unwrap_or_clone(rc2);assert!(ptr::eq(ptr, inner.as_ptr()));Source§impl<A>Rc<dynAny, A>where A:Allocator,
impl<A>Rc<dynAny, A>where A:Allocator,
1.29.0 ·Sourcepub fndowncast<T>(self) ->Result<Rc<T, A>,Rc<dynAny, A>>where T:Any,
pub fndowncast<T>(self) ->Result<Rc<T, A>,Rc<dynAny, A>>where T:Any,
Attempts to downcast theRc<dyn Any> to a concrete type.
§Examples
Sourcepub unsafe fndowncast_unchecked<T>(self) ->Rc<T, A>where T:Any,
🔬This is a nightly-only experimental API. (downcast_unchecked #90850)
pub unsafe fndowncast_unchecked<T>(self) ->Rc<T, A>where T:Any,
downcast_unchecked #90850)Downcasts theRc<dyn Any> to a concrete type.
For a safe alternative seedowncast.
§Examples
#![feature(downcast_unchecked)]usestd::any::Any;usestd::rc::Rc;letx: Rc<dynAny> = Rc::new(1_usize);unsafe{assert_eq!(*x.downcast_unchecked::<usize>(),1);}§Safety
The contained value must be of typeT. Calling this methodwith the incorrect type isundefined behavior.
Trait Implementations§
Source§impl<T, A>Allocator forRc<T, A>
impl<T, A>Allocator forRc<T, A>
Source§fnallocate(&self, layout:Layout) ->Result<NonNull<[u8]>,AllocError>
fnallocate(&self, layout:Layout) ->Result<NonNull<[u8]>,AllocError>
allocator_api #32838)Source§fnallocate_zeroed(&self, layout:Layout) ->Result<NonNull<[u8]>,AllocError>
fnallocate_zeroed(&self, layout:Layout) ->Result<NonNull<[u8]>,AllocError>
allocator_api #32838)allocate, but also ensures that the returned memory is zero-initialized.Read moreSource§unsafe fndeallocate(&self, ptr:NonNull<u8>, layout:Layout)
unsafe fndeallocate(&self, ptr:NonNull<u8>, layout:Layout)
allocator_api #32838)ptr.Read moreSource§unsafe fngrow( &self, ptr:NonNull<u8>, old_layout:Layout, new_layout:Layout,) ->Result<NonNull<[u8]>,AllocError>
unsafe fngrow( &self, ptr:NonNull<u8>, old_layout:Layout, new_layout:Layout,) ->Result<NonNull<[u8]>,AllocError>
allocator_api #32838)Source§unsafe fngrow_zeroed( &self, ptr:NonNull<u8>, old_layout:Layout, new_layout:Layout,) ->Result<NonNull<[u8]>,AllocError>
unsafe fngrow_zeroed( &self, ptr:NonNull<u8>, old_layout:Layout, new_layout:Layout,) ->Result<NonNull<[u8]>,AllocError>
allocator_api #32838)grow, but also ensures that the new contents are set to zero before beingreturned.Read more1.69.0 ·Source§impl<T:AsFd + ?Sized>AsFd forRc<T>
Available onUnix or HermitCore ortarget_os=trusty or WASI ortarget_os=motor only.
impl<T:AsFd + ?Sized>AsFd forRc<T>
target_os=trusty or WASI ortarget_os=motor only.Source§fnas_fd(&self) ->BorrowedFd<'_>
fnas_fd(&self) ->BorrowedFd<'_>
1.71.0 ·Source§impl<T:AsHandle + ?Sized>AsHandle forRc<T>
Available onWindows only.
impl<T:AsHandle + ?Sized>AsHandle forRc<T>
Source§fnas_handle(&self) ->BorrowedHandle<'_>
fnas_handle(&self) ->BorrowedHandle<'_>
1.69.0 ·Source§impl<T:AsRawFd>AsRawFd forRc<T>
Available onUnix or HermitCore ortarget_os=trusty or WASI ortarget_os=motor only.
impl<T:AsRawFd>AsRawFd forRc<T>
target_os=trusty or WASI ortarget_os=motor only.1.71.0 ·Source§impl<T:AsSocket>AsSocket forRc<T>
Available onWindows only.
impl<T:AsSocket>AsSocket forRc<T>
Source§fnas_socket(&self) ->BorrowedSocket<'_>
fnas_socket(&self) ->BorrowedSocket<'_>
1.0.0 ·Source§impl<T, A>Clone forRc<T, A>
impl<T, A>Clone forRc<T, A>
1.0.0 ·Source§impl<T, A>Drop forRc<T, A>
impl<T, A>Drop forRc<T, A>
Source§impl<W>From<Rc<W>> forLocalWakerwhere W:LocalWake + 'static,
impl<W>From<Rc<W>> forLocalWakerwhere W:LocalWake + 'static,
Source§fnfrom(waker:Rc<W>) ->LocalWaker
fnfrom(waker:Rc<W>) ->LocalWaker
Use aWake-able type as aLocalWaker.
No heap allocations or atomic operations are used for this conversion.
1.37.0 ·Source§impl<T>FromIterator<T> forRc<[T]>
impl<T>FromIterator<T> forRc<[T]>
Source§fnfrom_iter<I>(iter: I) ->Rc<[T]>where I:IntoIterator<Item = T>,
fnfrom_iter<I>(iter: I) ->Rc<[T]>where I:IntoIterator<Item = T>,
Takes each element in theIterator and collects it into anRc<[T]>.
§Performance characteristics
§The general case
In the general case, collecting intoRc<[T]> is done by firstcollecting into aVec<T>. That is, when writing the following:
this behaves as if we wrote:
letevens: 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.This will allocate as many times as needed for constructing theVec<T>and then it will allocate once for turning theVec<T> into theRc<[T]>.
§Iterators of known length
When yourIterator implementsTrustedLen and is of an exact size,a single allocation will be made for theRc<[T]>. For example:
1.0.0 ·Source§impl<T, A>Ord forRc<T, A>
impl<T, A>Ord forRc<T, A>
Source§fncmp(&self, other: &Rc<T, A>) ->Ordering
fncmp(&self, other: &Rc<T, A>) ->Ordering
1.21.0 ·Source§fnmax(self, other: Self) -> Selfwhere Self:Sized,
fnmax(self, other: Self) -> Selfwhere Self:Sized,
1.0.0 ·Source§impl<T, A>PartialEq forRc<T, A>
impl<T, A>PartialEq forRc<T, A>
Source§fneq(&self, other: &Rc<T, A>) ->bool
fneq(&self, other: &Rc<T, A>) ->bool
Equality for twoRcs.
TwoRcs are equal if their inner values are equal, even if they arestored in different allocation.
IfT also implementsEq (implying reflexivity of equality),twoRcs that point to the same allocation arealways equal.
§Examples
1.0.0 ·Source§impl<T, A>PartialOrd forRc<T, A>
impl<T, A>PartialOrd forRc<T, A>
Source§fnpartial_cmp(&self, other: &Rc<T, A>) ->Option<Ordering>
fnpartial_cmp(&self, other: &Rc<T, A>) ->Option<Ordering>
Partial comparison for twoRcs.
The two are compared by callingpartial_cmp() on their inner values.
§Examples
Source§fnlt(&self, other: &Rc<T, A>) ->bool
fnlt(&self, other: &Rc<T, A>) ->bool
Source§fnle(&self, other: &Rc<T, A>) ->bool
fnle(&self, other: &Rc<T, A>) ->bool
‘Less than or equal to’ comparison for twoRcs.
The two are compared by calling<= on their inner values.