Movatterモバイル変換


[0]ホーム

URL:


Rc

std::rc

StructRc 

1.0.0 ·Source
pub struct Rc<T, A =Global>
where A:Allocator, T: ?Sized,
{/* 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>

1.0.0 ·Source

pub fnnew(value: T) ->Rc<T>

Constructs a newRc<T>.

§Examples
usestd::rc::Rc;letfive = Rc::new(5);
1.60.0 ·Source

pub fnnew_cyclic<F>(data_fn: F) ->Rc<T>
where F:FnOnce(&Weak<T>) -> 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 ·Source

pub fnnew_uninit() ->Rc<MaybeUninit<T>>

Constructs a newRc with uninitialized contents.

§Examples
usestd::rc::Rc;letmutfive = Rc::<u32>::new_uninit();// Deferred initialization:Rc::get_mut(&mutfive).unwrap().write(5);letfive =unsafe{ five.assume_init() };assert_eq!(*five,5)
1.92.0 ·Source

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
usestd::rc::Rc;letzero = Rc::<u32>::new_zeroed();letzero =unsafe{ zero.assume_init() };assert_eq!(*zero,0)
Source

pub fntry_new(value: T) ->Result<Rc<T>,AllocError>

🔬This is a nightly-only experimental API. (allocator_api #32838)

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

§Examples
#![feature(allocator_api)]usestd::rc::Rc;letfive = Rc::try_new(5);
Source

pub fntry_new_uninit() ->Result<Rc<MaybeUninit<T>>,AllocError>

🔬This is a nightly-only experimental API. (allocator_api #32838)

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

§Examples
#![feature(allocator_api)]usestd::rc::Rc;letmutfive = Rc::<u32>::try_new_uninit()?;// Deferred initialization:Rc::get_mut(&mutfive).unwrap().write(5);letfive =unsafe{ five.assume_init() };assert_eq!(*five,5);
Source

pub fntry_new_zeroed() ->Result<Rc<MaybeUninit<T>>,AllocError>

🔬This is a nightly-only experimental API. (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
#![feature(allocator_api)]usestd::rc::Rc;letzero = Rc::<u32>::try_new_zeroed()?;letzero =unsafe{ zero.assume_init() };assert_eq!(*zero,0);
1.33.0 ·Source

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.

Source

pub fnmap<U>(this:Rc<T>, f: implFnOnce(&T) -> U) ->Rc<U>

🔬This is a nightly-only experimental API. (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
#![feature(smart_pointer_try_map)]usestd::rc::Rc;letr = Rc::new(7);letnew = Rc::map(r, |i| i +7);assert_eq!(*new,14);
Source

pub fntry_map<R>( this:Rc<T>, f: implFnOnce(&T) -> R,) -> <<R asTry>::Residual asResidual<Rc<<R asTry>::Output>>>::TryType
where R:Try, <R asTry>::Residual:Residual<Rc<<R asTry>::Output>>,

🔬This is a nightly-only experimental API. (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
#![feature(smart_pointer_try_map)]usestd::rc::Rc;letb = Rc::new(7);letnew = Rc::try_map(b, |&i| u32::try_from(i)).unwrap();assert_eq!(*new,7);
Source§

impl<T, A>Rc<T, A>
where A:Allocator,

Source

pub fnnew_in(value: T, alloc: A) ->Rc<T, A>

🔬This is a nightly-only experimental API. (allocator_api #32838)

Constructs a newRc in the provided allocator.

§Examples
#![feature(allocator_api)]usestd::rc::Rc;usestd::alloc::System;letfive = Rc::new_in(5, System);
Source

pub fnnew_uninit_in(alloc: A) ->Rc<MaybeUninit<T>, A>

🔬This is a nightly-only experimental API. (allocator_api #32838)

Constructs a newRc with uninitialized contents in the provided allocator.

§Examples
#![feature(get_mut_unchecked)]#![feature(allocator_api)]usestd::rc::Rc;usestd::alloc::System;letmutfive = Rc::<u32,_>::new_uninit_in(System);letfive =unsafe{// Deferred initialization:Rc::get_mut_unchecked(&mutfive).as_mut_ptr().write(5);    five.assume_init()};assert_eq!(*five,5)
Source

pub fnnew_zeroed_in(alloc: A) ->Rc<MaybeUninit<T>, A>

🔬This is a nightly-only experimental API. (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
#![feature(allocator_api)]usestd::rc::Rc;usestd::alloc::System;letzero = Rc::<u32,_>::new_zeroed_in(System);letzero =unsafe{ zero.assume_init() };assert_eq!(*zero,0)
Source

pub fnnew_cyclic_in<F>(data_fn: F, alloc: A) ->Rc<T, A>
where F:FnOnce(&Weak<T, A>) -> T,

🔬This is a nightly-only experimental API. (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.

Source

pub fntry_new_in(value: T, alloc: A) ->Result<Rc<T, A>,AllocError>

🔬This is a nightly-only experimental API. (allocator_api #32838)

Constructs a newRc<T> in the provided allocator, returning an error if the allocationfails

§Examples
#![feature(allocator_api)]usestd::rc::Rc;usestd::alloc::System;letfive = Rc::try_new_in(5, System);
Source

pub fntry_new_uninit_in(alloc: A) ->Result<Rc<MaybeUninit<T>, A>,AllocError>

🔬This is a nightly-only experimental API. (allocator_api #32838)

Constructs a newRc with uninitialized contents, in the provided allocator, returning anerror if the allocation fails

§Examples
#![feature(allocator_api)]#![feature(get_mut_unchecked)]usestd::rc::Rc;usestd::alloc::System;letmutfive = Rc::<u32,_>::try_new_uninit_in(System)?;letfive =unsafe{// Deferred initialization:Rc::get_mut_unchecked(&mutfive).as_mut_ptr().write(5);    five.assume_init()};assert_eq!(*five,5);
Source

pub fntry_new_zeroed_in(alloc: A) ->Result<Rc<MaybeUninit<T>, A>,AllocError>

🔬This is a nightly-only experimental API. (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
#![feature(allocator_api)]usestd::rc::Rc;usestd::alloc::System;letzero = Rc::<u32,_>::try_new_zeroed_in(System)?;letzero =unsafe{ zero.assume_init() };assert_eq!(*zero,0);
Source

pub fnpin_in(value: T, alloc: A) ->Pin<Rc<T, A>>
where A: 'static,

🔬This is a nightly-only experimental API. (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 ·Source

pub fntry_unwrap(this:Rc<T, A>) ->Result<T,Rc<T, A>>

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

Otherwise, anErr is returned with the sameRc that waspassed in.

This will succeed even if there are outstanding weak references.

§Examples
usestd::rc::Rc;letx = Rc::new(3);assert_eq!(Rc::try_unwrap(x),Ok(3));letx = Rc::new(4);let_y = Rc::clone(&x);assert_eq!(*Rc::try_unwrap(x).unwrap_err(),4);
1.70.0 ·Source

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
usestd::rc::Rc;letx = Rc::new(3);assert_eq!(Rc::into_inner(x),Some(3));letx = Rc::new(4);lety = Rc::clone(&x);assert_eq!(Rc::into_inner(y),None);assert_eq!(Rc::into_inner(x),Some(4));
Source§

impl<T>Rc<[T]>

1.82.0 ·Source

pub fnnew_uninit_slice(len:usize) ->Rc<[MaybeUninit<T>]>

Constructs a new reference-counted slice with uninitialized contents.

§Examples
usestd::rc::Rc;letmutvalues = Rc::<[u32]>::new_uninit_slice(3);// Deferred initialization:letdata = Rc::get_mut(&mutvalues).unwrap();data[0].write(1);data[1].write(2);data[2].write(3);letvalues =unsafe{ values.assume_init() };assert_eq!(*values, [1,2,3])
1.92.0 ·Source

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
usestd::rc::Rc;letvalues = Rc::<[u32]>::new_zeroed_slice(3);letvalues =unsafe{ values.assume_init() };assert_eq!(*values, [0,0,0])
Source

pub fninto_array<const N:usize>(self) ->Option<Rc<[T; N]>>

🔬This is a nightly-only experimental API. (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,

Source

pub fnnew_uninit_slice_in(len:usize, alloc: A) ->Rc<[MaybeUninit<T>], A>

🔬This is a nightly-only experimental API. (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])
Source

pub fnnew_zeroed_slice_in(len:usize, alloc: A) ->Rc<[MaybeUninit<T>], A>

🔬This is a nightly-only experimental API. (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
#![feature(allocator_api)]usestd::rc::Rc;usestd::alloc::System;letvalues = Rc::<[u32],_>::new_zeroed_slice_in(3, System);letvalues =unsafe{ values.assume_init() };assert_eq!(*values, [0,0,0])
Source§

impl<T, A>Rc<MaybeUninit<T>, A>
where A:Allocator,

1.82.0 ·Source

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
usestd::rc::Rc;letmutfive = Rc::<u32>::new_uninit();// Deferred initialization:Rc::get_mut(&mutfive).unwrap().write(5);letfive =unsafe{ five.assume_init() };assert_eq!(*five,5)
Source§

impl<T>Rc<T>
where T:CloneToUninit + ?Sized,

Source

pub fnclone_from_ref(value:&T) ->Rc<T>

🔬This is a nightly-only experimental API. (clone_from_ref #149075)

Constructs a newRc<T> with a clone ofvalue.

§Examples
#![feature(clone_from_ref)]usestd::rc::Rc;lethello: Rc<str> = Rc::clone_from_ref("hello");
Source

pub fntry_clone_from_ref(value:&T) ->Result<Rc<T>,AllocError>

🔬This is a nightly-only experimental API. (clone_from_ref #149075)

Constructs a newRc<T> with a clone ofvalue, returning an error if allocation fails

§Examples
#![feature(clone_from_ref)]#![feature(allocator_api)]usestd::rc::Rc;lethello: Rc<str> = Rc::try_clone_from_ref("hello")?;
Source§

impl<T, A>Rc<T, A>

Source

pub fnclone_from_ref_in(value:&T, alloc: A) ->Rc<T, A>

🔬This is a nightly-only experimental API. (clone_from_ref #149075)

Constructs a newRc<T> with a clone ofvalue in the provided allocator.

§Examples
#![feature(clone_from_ref)]#![feature(allocator_api)]usestd::rc::Rc;usestd::alloc::System;lethello: Rc<str, System> = Rc::clone_from_ref_in("hello", System);
Source

pub 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)

Constructs a newRc<T> with a clone ofvalue in the provided allocator, returning an error if allocation fails

§Examples
#![feature(clone_from_ref)]#![feature(allocator_api)]usestd::rc::Rc;usestd::alloc::System;lethello: Rc<str, System> = Rc::try_clone_from_ref_in("hello", System)?;
Source§

impl<T, A>Rc<[MaybeUninit<T>], A>
where A:Allocator,

1.82.0 ·Source

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
usestd::rc::Rc;letmutvalues = Rc::<[u32]>::new_uninit_slice(3);// Deferred initialization:letdata = Rc::get_mut(&mutvalues).unwrap();data[0].write(1);data[1].write(2);data[2].write(3);letvalues =unsafe{ values.assume_init() };assert_eq!(*values, [1,2,3])
Source§

impl<T>Rc<T>
where T: ?Sized,

1.17.0 ·Source

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:

  • IfU is sized, it must have the same size and alignment asT. Thisis trivially true ifU isT.
  • IfU is 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:

usestd::rc::Rc;letx: Rc<[u32]> = Rc::new([1,2,3]);letx_ptr:*const[u32] = Rc::into_raw(x);unsafe{letx: Rc<[u32;3]> = Rc::from_raw(x_ptr.cast::<[u32;3]>());assert_eq!(&*x,&[1,2,3]);}
1.17.0 ·Source

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
usestd::rc::Rc;letx = Rc::new("hello".to_owned());letx_ptr = Rc::into_raw(x);assert_eq!(unsafe{&*x_ptr },"hello");
1.53.0 ·Source

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
usestd::rc::Rc;letfive = Rc::new(5);unsafe{letptr = Rc::into_raw(five);    Rc::increment_strong_count(ptr);letfive = Rc::from_raw(ptr);assert_eq!(2, Rc::strong_count(&five));}
1.53.0 ·Source

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
usestd::rc::Rc;letfive = Rc::new(5);unsafe{letptr = Rc::into_raw(five);    Rc::increment_strong_count(ptr);letfive = Rc::from_raw(ptr);assert_eq!(2, Rc::strong_count(&five));    Rc::decrement_strong_count(ptr);assert_eq!(1, Rc::strong_count(&five));}
Source§

impl<T, A>Rc<T, A>
where A:Allocator, T: ?Sized,

Source

pub fnallocator(this: &Rc<T, A>) ->&A

🔬This is a nightly-only experimental API. (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.

Source

pub fninto_raw_with_allocator(this:Rc<T, A>) -> (*const T, A)

🔬This is a nightly-only experimental API. (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
#![feature(allocator_api)]usestd::rc::Rc;usestd::alloc::System;letx = Rc::new_in("hello".to_owned(), System);let(ptr, alloc) = Rc::into_raw_with_allocator(x);assert_eq!(unsafe{&*ptr },"hello");letx =unsafe{ Rc::from_raw_in(ptr, alloc) };assert_eq!(&*x,"hello");
1.45.0 ·Source

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
usestd::rc::Rc;letx = Rc::new(0);lety = Rc::clone(&x);letx_ptr = Rc::as_ptr(&x);assert_eq!(x_ptr, Rc::as_ptr(&y));assert_eq!(unsafe{*x_ptr },0);
Source

pub unsafe fnfrom_raw_in(ptr:*const T, alloc: A) ->Rc<T, A>

🔬This is a nightly-only experimental API. (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:

  • IfU is sized, it must have the same size and alignment asT. Thisis trivially true ifU isT.
  • IfU is 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:

#![feature(allocator_api)]usestd::rc::Rc;usestd::alloc::System;letx: Rc<[u32],_> = Rc::new_in([1,2,3], System);letx_ptr:*const[u32] = Rc::into_raw_with_allocator(x).0;unsafe{letx: Rc<[u32;3],_> = Rc::from_raw_in(x_ptr.cast::<[u32;3]>(), System);assert_eq!(&*x,&[1,2,3]);}
1.4.0 ·Source

pub fndowngrade(this: &Rc<T, A>) ->Weak<T, A>
where A:Clone,

Creates a newWeak pointer to this allocation.

§Examples
usestd::rc::Rc;letfive = Rc::new(5);letweak_five = Rc::downgrade(&five);
1.15.0 ·Source

pub fnweak_count(this: &Rc<T, A>) ->usize

Gets the number ofWeak pointers to this allocation.

§Examples
usestd::rc::Rc;letfive = Rc::new(5);let_weak_five = Rc::downgrade(&five);assert_eq!(1, Rc::weak_count(&five));
1.15.0 ·Source

pub fnstrong_count(this: &Rc<T, A>) ->usize

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

§Examples
usestd::rc::Rc;letfive = Rc::new(5);let_also_five = Rc::clone(&five);assert_eq!(2, Rc::strong_count(&five));
Source

pub unsafe fnincrement_strong_count_in(ptr:*const T, alloc: A)
where A:Clone,

🔬This is a nightly-only experimental API. (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
#![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));}
Source

pub unsafe fndecrement_strong_count_in(ptr:*const T, alloc: A)

🔬This is a nightly-only experimental API. (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 ·Source

pub fnget_mut(this: &mutRc<T, A>) ->Option<&mut T>

Returns a mutable reference into the givenRc, if there areno otherRc orWeak pointers to the same allocation.

ReturnsNone otherwise, because it is not safe tomutate a shared value.

See alsomake_mut, which willclonethe inner value when there are otherRc pointers.

§Examples
usestd::rc::Rc;letmutx = Rc::new(3);*Rc::get_mut(&mutx).unwrap() =4;assert_eq!(*x,4);let_y = Rc::clone(&x);assert!(Rc::get_mut(&mutx).is_none());
Source

pub unsafe fnget_mut_unchecked(this: &mutRc<T, A>) ->&mut T

🔬This is a nightly-only experimental API. (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 str

OtherRc 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-free
1.17.0 ·Source

pub fnptr_eq(this: &Rc<T, A>, other: &Rc<T, A>) ->bool

Returnstrue if the twoRcs point to the same allocation in a vein similar toptr::eq. This function ignores the metadata ofdyn Trait pointers.

§Examples
usestd::rc::Rc;letfive = Rc::new(5);letsame_five = Rc::clone(&five);letother_five = Rc::new(5);assert!(Rc::ptr_eq(&five,&same_five));assert!(!Rc::ptr_eq(&five,&other_five));
Source§

impl<T, A>Rc<T, A>

1.4.0 ·Source

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:

usestd::rc::Rc;letmutdata = Rc::new(75);letweak = Rc::downgrade(&data);assert!(75==*data);assert!(75==*weak.upgrade().unwrap());*Rc::make_mut(&mutdata) +=1;assert!(76==*data);assert!(weak.upgrade().is_none());
Source§

impl<T, A>Rc<T, A>
where T:Clone, A:Allocator,

1.76.0 ·Source

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,

1.29.0 ·Source

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
usestd::any::Any;usestd::rc::Rc;fnprint_if_string(value: Rc<dynAny>) {if letOk(string) = value.downcast::<String>() {println!("String ({}): {}", string.len(), string);    }}letmy_string ="Hello World".to_string();print_if_string(Rc::new(my_string));print_if_string(Rc::new(0i8));
Source

pub unsafe fndowncast_unchecked<T>(self) ->Rc<T, A>
where T:Any,

🔬This is a nightly-only experimental API. (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>
where T:Allocator + ?Sized, A:Allocator,

Source§

fnallocate(&self, layout:Layout) ->Result<NonNull<[u8]>,AllocError>

🔬This is a nightly-only experimental API. (allocator_api #32838)
Attempts to allocate a block of memory.Read more
Source§

fnallocate_zeroed(&self, layout:Layout) ->Result<NonNull<[u8]>,AllocError>

🔬This is a nightly-only experimental API. (allocator_api #32838)
Behaves likeallocate, but also ensures that the returned memory is zero-initialized.Read more
Source§

unsafe fndeallocate(&self, ptr:NonNull<u8>, layout:Layout)

🔬This is a nightly-only experimental API. (allocator_api #32838)
Deallocates the memory referenced byptr.Read more
Source§

unsafe fngrow( &self, ptr:NonNull<u8>, old_layout:Layout, new_layout:Layout,) ->Result<NonNull<[u8]>,AllocError>

🔬This is a nightly-only experimental API. (allocator_api #32838)
Attempts to extend the memory block.Read more
Source§

unsafe fngrow_zeroed( &self, ptr:NonNull<u8>, old_layout:Layout, new_layout:Layout,) ->Result<NonNull<[u8]>,AllocError>

🔬This is a nightly-only experimental API. (allocator_api #32838)
Behaves likegrow, but also ensures that the new contents are set to zero before beingreturned.Read more
Source§

unsafe fnshrink( &self, ptr:NonNull<u8>, old_layout:Layout, new_layout:Layout,) ->Result<NonNull<[u8]>,AllocError>

🔬This is a nightly-only experimental API. (allocator_api #32838)
Attempts to shrink the memory block.Read more
Source§

fnby_ref(&self) -> &Self
where Self:Sized,

🔬This is a nightly-only experimental API. (allocator_api #32838)
Creates a “by reference” adapter for this instance ofAllocator.Read more
1.69.0 ·Source§

impl<T:AsFd + ?Sized>AsFd forRc<T>

Available onUnix or HermitCore ortarget_os=trusty or WASI ortarget_os=motor only.
Source§

fnas_fd(&self) ->BorrowedFd<'_>

Borrows the file descriptor.Read more
1.71.0 ·Source§

impl<T:AsHandle + ?Sized>AsHandle forRc<T>

Available onWindows only.
Source§

fnas_handle(&self) ->BorrowedHandle<'_>

Borrows the handle.Read more
1.69.0 ·Source§

impl<T:AsRawFd>AsRawFd forRc<T>

Available onUnix or HermitCore ortarget_os=trusty or WASI ortarget_os=motor only.
Source§

fnas_raw_fd(&self) ->RawFd

Extracts the raw file descriptor.Read more
1.5.0 ·Source§

impl<T, A>AsRef<T> forRc<T, A>
where A:Allocator, T: ?Sized,

Source§

fnas_ref(&self) ->&T

Converts this type into a shared reference of the (usually inferred) input type.
1.71.0 ·Source§

impl<T:AsSocket>AsSocket forRc<T>

Available onWindows only.
Source§

fnas_socket(&self) ->BorrowedSocket<'_>

Borrows the socket.
1.0.0 ·Source§

impl<T, A>Borrow<T> forRc<T, A>
where A:Allocator, T: ?Sized,

Source§

fnborrow(&self) ->&T

Immutably borrows from an owned value.Read more
1.0.0 ·Source§

impl<T, A>Clone forRc<T, A>
where A:Allocator +Clone, T: ?Sized,

Source§

fnclone(&self) ->Rc<T, A>

Makes a clone of theRc pointer.

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

§Examples
usestd::rc::Rc;letfive = Rc::new(5);let _= Rc::clone(&five);
1.0.0 ·Source§

fnclone_from(&mut self, source: &Self)

Performs copy-assignment fromsource.Read more
1.0.0 ·Source§

impl<T, A>Debug forRc<T, A>
where T:Debug + ?Sized, A:Allocator,

Source§

fnfmt(&self, f: &mutFormatter<'_>) ->Result<(),Error>

Formats the value using the given formatter.Read more
1.91.0 ·Source§

impl<T>Default forPin<Rc<T>>
whereRc<T>:Default, T: ?Sized,

Source§

fndefault() ->Pin<Rc<T>>

Returns the “default value” for a type.Read more
1.80.0 ·Source§

impl<T>Default forRc<[T]>

Source§

fndefault() ->Rc<[T]>

Creates an empty[T] inside anRc.

This may or may not share an allocation with other Rcs on the same thread.

1.80.0 ·Source§

implDefault forRc<CStr>

Source§

fndefault() ->Rc<CStr>

Creates an empty CStr inside an Rc

This may or may not share an allocation with other Rcs on the same thread.

1.0.0 ·Source§

impl<T>Default forRc<T>
where T:Default,

Source§

fndefault() ->Rc<T>

Creates a newRc<T>, with theDefault value forT.

§Examples
usestd::rc::Rc;letx: Rc<i32> = Default::default();assert_eq!(*x,0);
1.80.0 ·Source§

implDefault forRc<str>

Source§

fndefault() ->Rc<str>

Creates an emptystr inside anRc.

This may or may not share an allocation with other Rcs on the same thread.

1.0.0 ·Source§

impl<T, A>Deref forRc<T, A>
where A:Allocator, T: ?Sized,

Source§

typeTarget = T

The resulting type after dereferencing.
Source§

fnderef(&self) ->&T

Dereferences the value.
1.0.0 ·Source§

impl<T, A>Display forRc<T, A>
where T:Display + ?Sized, A:Allocator,

Source§

fnfmt(&self, f: &mutFormatter<'_>) ->Result<(),Error>

Formats the value using the given formatter.Read more
1.0.0 ·Source§

impl<T, A>Drop forRc<T, A>
where A:Allocator, T: ?Sized,

Source§

fndrop(&mut self)

Drops theRc.

This will decrement the strong reference count. If the strong referencecount reaches zero then the only other references (if any) areWeak, so wedrop the inner value.

§Examples
usestd::rc::Rc;structFoo;implDropforFoo {fndrop(&mutself) {println!("dropped!");    }}letfoo  = Rc::new(Foo);letfoo2 = Rc::clone(&foo);drop(foo);// Doesn't print anythingdrop(foo2);// Prints "dropped!"
1.21.0 ·Source§

impl<T>From<&[T]> forRc<[T]>
where T:Clone,

Source§

fnfrom(v: &[T]) ->Rc<[T]>

Allocates a reference-counted slice and fills it by cloningv’s items.

§Example
letoriginal:&[i32] =&[1,2,3];letshared: Rc<[i32]> = Rc::from(original);assert_eq!(&[1,2,3],&shared[..]);
1.24.0 ·Source§

implFrom<&CStr> forRc<CStr>

Source§

fnfrom(s: &CStr) ->Rc<CStr>

Converts a&CStr into aRc<CStr>,by copying the contents into a newly allocatedRc.

1.24.0 ·Source§

implFrom<&OsStr> forRc<OsStr>

Source§

fnfrom(s: &OsStr) ->Rc<OsStr>

Copies the string into a newly allocatedRc<OsStr>.

1.24.0 ·Source§

implFrom<&Path> forRc<Path>

Source§

fnfrom(s: &Path) ->Rc<Path>

Converts aPath into anRc by copying thePath data into a newRc buffer.

1.84.0 ·Source§

impl<T>From<&mut[T]> forRc<[T]>
where T:Clone,

Source§

fnfrom(v: &mut[T]) ->Rc<[T]>

Allocates a reference-counted slice and fills it by cloningv’s items.

§Example
letmutoriginal = [1,2,3];letoriginal:&mut[i32] =&mutoriginal;letshared: Rc<[i32]> = Rc::from(original);assert_eq!(&[1,2,3],&shared[..]);
1.84.0 ·Source§

implFrom<&mutCStr> forRc<CStr>

Source§

fnfrom(s: &mutCStr) ->Rc<CStr>

Converts a&mut CStr into aRc<CStr>,by copying the contents into a newly allocatedRc.

1.84.0 ·Source§

implFrom<&mutOsStr> forRc<OsStr>

Source§

fnfrom(s: &mutOsStr) ->Rc<OsStr>

Copies the string into a newly allocatedRc<OsStr>.

1.84.0 ·Source§

implFrom<&mutPath> forRc<Path>

Source§

fnfrom(s: &mutPath) ->Rc<Path>

Converts aPath into anRc by copying thePath data into a newRc buffer.

1.84.0 ·Source§

implFrom<&mutstr> forRc<str>

Source§

fnfrom(v: &mutstr) ->Rc<str>

Allocates a reference-counted string slice and copiesv into it.

§Example
letmutoriginal = String::from("statue");letoriginal:&mutstr =&mutoriginal;letshared: Rc<str> = Rc::from(original);assert_eq!("statue",&shared[..]);
1.21.0 ·Source§

implFrom<&str> forRc<str>

Source§

fnfrom(v: &str) ->Rc<str>

Allocates a reference-counted string slice and copiesv into it.

§Example
letshared: Rc<str> = Rc::from("statue");assert_eq!("statue",&shared[..]);
1.74.0 ·Source§

impl<T, const N:usize>From<[T; N]> forRc<[T]>

Source§

fnfrom(v:[T; N]) ->Rc<[T]>

Converts a[T; N] into anRc<[T]>.

The conversion moves the array into a newly allocatedRc.

§Example
letoriginal: [i32;3] = [1,2,3];letshared: Rc<[i32]> = Rc::from(original);assert_eq!(&[1,2,3],&shared[..]);
1.21.0 ·Source§

impl<T, A>From<Box<T, A>> forRc<T, A>
where A:Allocator, T: ?Sized,

Source§

fnfrom(v:Box<T, A>) ->Rc<T, A>

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

§Example
letoriginal: Box<i32> = Box::new(1);letshared: Rc<i32> = Rc::from(original);assert_eq!(1,*shared);
1.24.0 ·Source§

implFrom<CString> forRc<CStr>

Source§

fnfrom(s:CString) ->Rc<CStr>

Converts aCString into anRc<CStr> by moving theCStringdata into a newRc buffer.

1.45.0 ·Source§

impl<'a, B>From<Cow<'a, B>> forRc<B>
where B:ToOwned + ?Sized,Rc<B>:From<&'a B> +From<<B asToOwned>::Owned>,

Source§

fnfrom(cow:Cow<'a, B>) ->Rc<B>

Creates a reference-counted pointer from a clone-on-write pointer bycopying its content.

§Example
letcow: Cow<'_, str> = Cow::Borrowed("eggplant");letshared: Rc<str> = Rc::from(cow);assert_eq!("eggplant",&shared[..]);
1.24.0 ·Source§

implFrom<OsString> forRc<OsStr>

Source§

fnfrom(s:OsString) ->Rc<OsStr>

Converts anOsString into anRc<OsStr> by moving theOsStringdata into a newRc buffer.

1.24.0 ·Source§

implFrom<PathBuf> forRc<Path>

Source§

fnfrom(s:PathBuf) ->Rc<Path>

Converts aPathBuf into anRc<Path> by moving thePathBuf data intoa newRc buffer.

Source§

implFrom<Rc<[u8]>> forRc<ByteStr>

Available onnon-no_rc only.
Source§

fnfrom(s:Rc<[u8]>) ->Rc<ByteStr>

Converts to this type from the input type.
Source§

implFrom<Rc<ByteStr>> forRc<[u8]>

Available onnon-no_rc only.
Source§

fnfrom(s:Rc<ByteStr>) ->Rc<[u8]>

Converts to this type from the input type.
Source§

impl<W>From<Rc<W>> forLocalWaker
where W:LocalWake + 'static,

Source§

fnfrom(waker:Rc<W>) ->LocalWaker

Use aWake-able type as aLocalWaker.

No heap allocations or atomic operations are used for this conversion.

Source§

impl<W>From<Rc<W>> forRawWaker
where W:LocalWake + 'static,

Source§

fnfrom(waker:Rc<W>) ->RawWaker

Use aWake-able type as aRawWaker.

No heap allocations or atomic operations are used for this conversion.

1.62.0 ·Source§

implFrom<Rc<str>> forRc<[u8]>

Source§

fnfrom(rc:Rc<str>) ->Rc<[u8]>

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

§Example
letstring: Rc<str> = Rc::from("eggplant");letbytes: Rc<[u8]> = Rc::from(string);assert_eq!("eggplant".as_bytes(), bytes.as_ref());
1.21.0 ·Source§

implFrom<String> forRc<str>

Source§

fnfrom(v:String) ->Rc<str>

Allocates a reference-counted string slice and copiesv into it.

§Example
letoriginal: String ="statue".to_owned();letshared: Rc<str> = Rc::from(original);assert_eq!("statue",&shared[..]);
1.6.0 ·Source§

impl<T>From<T> forRc<T>

Source§

fnfrom(t: T) ->Rc<T>

Converts a generic typeT into anRc<T>

The conversion allocates on the heap and movestfrom the stack into it.

§Example
letx =5;letrc = Rc::new(5);assert_eq!(Rc::from(x), rc);
1.21.0 ·Source§

impl<T, A>From<Vec<T, A>> forRc<[T], A>
where A:Allocator,

Source§

fnfrom(v:Vec<T, A>) ->Rc<[T], A>

Allocates a reference-counted slice and movesv’s items into it.

§Example
letunique: Vec<i32> =vec![1,2,3];letshared: Rc<[i32]> = Rc::from(unique);assert_eq!(&[1,2,3],&shared[..]);
1.37.0 ·Source§

impl<T>FromIterator<T> forRc<[T]>

Source§

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:

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

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:

letevens: Rc<[u8]> = (0..10).collect();// Just a single allocation happens here.
1.0.0 ·Source§

impl<T, A>Hash forRc<T, A>
where T:Hash + ?Sized, A:Allocator,

Source§

fnhash<H>(&self, state:&mut H)
where H:Hasher,

Feeds this value into the givenHasher.Read more
1.3.0 ·Source§

fnhash_slice<H>(data: &[Self], state:&mut H)
where H:Hasher, Self:Sized,

Feeds a slice of this type into the givenHasher.Read more
1.0.0 ·Source§

impl<T, A>Ord forRc<T, A>
where T:Ord + ?Sized, A:Allocator,

Source§

fncmp(&self, other: &Rc<T, A>) ->Ordering

Comparison for twoRcs.

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

§Examples
usestd::rc::Rc;usestd::cmp::Ordering;letfive = Rc::new(5);assert_eq!(Ordering::Less, five.cmp(&Rc::new(6)));
1.21.0 ·Source§

fnmax(self, other: Self) -> Self
where Self:Sized,

Compares and returns the maximum of two values.Read more
1.21.0 ·Source§

fnmin(self, other: Self) -> Self
where Self:Sized,

Compares and returns the minimum of two values.Read more
1.50.0 ·Source§

fnclamp(self, min: Self, max: Self) -> Self
where Self:Sized,

Restrict a value to a certain interval.Read more
1.0.0 ·Source§

impl<T, A>PartialEq forRc<T, A>
where T:PartialEq + ?Sized, A:Allocator,

Source§

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
usestd::rc::Rc;letfive = Rc::new(5);assert!(five == Rc::new(5));
Source§

fnne(&self, other: &Rc<T, A>) ->bool

Inequality for twoRcs.

TwoRcs are not equal if their inner values are not equal.

IfT also implementsEq (implying reflexivity of equality),twoRcs that point to the same allocation arealways equal.

§Examples
usestd::rc::Rc;letfive = Rc::new(5);assert!(five != Rc::new(6));
1.0.0 ·Source§

impl<T, A>PartialOrd forRc<T, A>
where T:PartialOrd + ?Sized, A:Allocator,

Source§

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
usestd::rc::Rc;usestd::cmp::Ordering;letfive = Rc::new(5);assert_eq!(Some(Ordering::Less), five.partial_cmp(&Rc::new(6)));
Source§

fnlt(&self, other: &Rc<T, A>) ->bool

Less-than comparison for twoRcs.

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

§Examples
usestd::rc::Rc;letfive = Rc::new(5);assert!(five < Rc::new(6));
Source§

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.

§Examples
usestd::rc::Rc;letfive = Rc::new(5);assert!(five <= Rc::new(5));
Source§

fngt(&self, other: &Rc<T, A>) ->bool

Greater-than comparison for twoRcs.

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

§Examples
usestd::rc::Rc;letfive = Rc::new(5);assert!(five > Rc::new(4));
Source§

fnge(&self, other: &Rc<T, A>) ->bool

‘Greater than or equal to’ comparison for twoRcs.

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

§Examples
usestd::rc::Rc;letfive = Rc::new(5);assert!(five >= Rc::new(5));
1.0.0 ·Source§

impl<T, A>Pointer forRc<T, A>
where A:Allocator, T: ?Sized,

Source§

fnfmt(&self, f: &mutFormatter<'_>) ->Result<(),Error>

Formats the value using the given formatter.Read more
1.43.0 ·Source§

impl<T, A, const N:usize>TryFrom<Rc<[T], A>> forRc<[T; N], A>
where A:Allocator,

Source§

typeError =Rc<[T], A>

The type returned in the event of a conversion error.
Source§

fntry_from( boxed_slice:Rc<[T], A>,) ->Result<Rc<[T; N], A>, <Rc<[T; N], A> asTryFrom<Rc<[T], A>>>::Error>

Performs the conversion.
Source§

impl<T>CloneFromCell forRc<T>
where T: ?Sized,

Source§

impl<T, U, A>CoerceUnsized<Rc<U, A>> forRc<T, A>
where T:Unsize<U> + ?Sized, A:Allocator, U: ?Sized,

Source§

impl<T, A>DerefPure forRc<T, A>
where A:Allocator, T: ?Sized,

Source§

impl<T, U>DispatchFromDyn<Rc<U>> forRc<T>
where T:Unsize<U> + ?Sized, U: ?Sized,

1.0.0 ·Source§

impl<T, A>Eq forRc<T, A>
where T:Eq + ?Sized, A:Allocator,

Source§

impl<T, A>PinCoerceUnsized forRc<T, A>
where A:Allocator, T: ?Sized,

1.58.0 ·Source§

impl<T, A>RefUnwindSafe forRc<T, A>

1.0.0 ·Source§

impl<T, A> !Send forRc<T, A>
where A:Allocator, T: ?Sized,

1.0.0 ·Source§

impl<T, A> !Sync forRc<T, A>
where A:Allocator, T: ?Sized,

1.33.0 ·Source§

impl<T, A>Unpin forRc<T, A>
where A:Allocator, T: ?Sized,

1.9.0 ·Source§

impl<T, A>UnwindSafe forRc<T, A>

Source§

impl<T, A>UseCloned forRc<T, A>
where A:Allocator +Clone, T: ?Sized,

Auto Trait Implementations§

§

impl<T, A>Freeze forRc<T, A>
where A:Freeze, T: ?Sized,

Blanket Implementations§

Source§

impl<T>Any for T
where T: 'static + ?Sized,

Source§

fntype_id(&self) ->TypeId

Gets theTypeId ofself.Read more
Source§

impl<T>Borrow<T> for T
where T: ?Sized,

Source§

fnborrow(&self) ->&T

Immutably borrows from an owned value.Read more
Source§

impl<T>BorrowMut<T> for T
where T: ?Sized,

Source§

fnborrow_mut(&mut self) ->&mut T

Mutably borrows from an owned value.Read more
Source§

impl<T>CloneToUninit for T
where T:Clone,

Source§

unsafe fnclone_to_uninit(&self, dest:*mutu8)

🔬This is a nightly-only experimental API. (clone_to_uninit #126799)
Performs copy-assignment fromself todest.Read more
Source§

impl<T>From<!> for T

Source§

fnfrom(t:!) -> T

Converts to this type from the input type.
Source§

impl<T>From<T> for T

Source§

fnfrom(t: T) -> T

Returns the argument unchanged.

Source§

impl<T, U>Into<U> for T
where U:From<T>,

Source§

fninto(self) -> U

CallsU::from(self).

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

Source§

impl<P, T>Receiver for P
where P:Deref<Target = T> + ?Sized, T: ?Sized,

Source§

typeTarget = T

🔬This is a nightly-only experimental API. (arbitrary_self_types #44874)
The target type on which the method may be called.
Source§

impl<T>ToOwned for T
where T:Clone,

Source§

typeOwned = T

The resulting type after obtaining ownership.
Source§

fnto_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning.Read more
Source§

fnclone_into(&self, target:&mut T)

Uses borrowed data to replace owned data, usually by cloning.Read more
Source§

impl<T>ToString for T
where T:Display + ?Sized,

Source§

fnto_string(&self) ->String

Converts the given value to aString.Read more
Source§

impl<T, U>TryFrom<U> for T
where U:Into<T>,

Source§

typeError =Infallible

The type returned in the event of a conversion error.
Source§

fntry_from(value: U) ->Result<T, <T asTryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U>TryInto<U> for T
where U:TryFrom<T>,

Source§

typeError = <U asTryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fntry_into(self) ->Result<U, <U asTryFrom<T>>::Error>

Performs the conversion.

[8]ページ先頭

©2009-2026 Movatter.jp