Movatterモバイル変換


[0]ホーム

URL:


Arc

std::sync

StructArc 

1.0.0 ·Source
pub struct Arc<T, A =Global>
where A:Allocator, T: ?Sized,
{/* private fields */ }
Expand description

A thread-safe reference-counting pointer. ‘Arc’ stands for ‘AtomicallyReference Counted’.

The typeArc<T> provides shared ownership of a value of typeT,allocated in the heap. Invokingclone onArc producesa newArc instance, which points to the same allocation on the heap as thesourceArc, while increasing a reference count. When the lastArcpointer to a given allocation is destroyed, the value stored in that allocation (oftenreferred to as “inner value”) is also dropped.

Shared references in Rust disallow mutation by default, andArc is noexception: you cannot generally obtain a mutable reference to somethinginside anArc. If you do need to mutate through anArc, you have several options:

  1. Use interior mutability with synchronization primitives likeMutex,RwLock, or one of theAtomic types.

  2. Use clone-on-write semantics withArc::make_mut which provides efficient mutationwithout requiring interior mutability. This approach clones the data only whenneeded (when there are multiple references) and can be more efficient when mutationsare infrequent.

  3. UseArc::get_mut when you know yourArc is not shared (has a reference count of 1),which provides direct mutable access to the inner value without any cloning.

usestd::sync::Arc;letmutdata = Arc::new(vec![1,2,3]);// This will clone the vector only if there are other references to itArc::make_mut(&mutdata).push(4);assert_eq!(*data,vec![1,2,3,4]);

Note: This type is only available on platforms that support atomicloads and stores of pointers, which includes all platforms that supportthestd crate but not all those which only supportalloc.This may be detected at compile time using#[cfg(target_has_atomic = "ptr")].

§Thread Safety

UnlikeRc<T>,Arc<T> uses atomic operations for its referencecounting. This means that it is thread-safe. The disadvantage is thatatomic operations are more expensive than ordinary memory accesses. If youare not sharing reference-counted allocations between threads, consider usingRc<T> for lower overhead.Rc<T> is a safe default, because thecompiler will catch any attempt to send anRc<T> between threads.However, a library might chooseArc<T> in order to give library consumersmore flexibility.

Arc<T> will implementSend andSync as long as theT implementsSend andSync. Why can’t you put a non-thread-safe typeT in anArc<T> to make it thread-safe? This may be a bit counter-intuitive atfirst: after all, isn’t the point ofArc<T> thread safety? The key isthis:Arc<T> makes it thread safe to have multiple ownership of the samedata, but it doesn’t add thread safety to its data. ConsiderArc<RefCell<T>>.RefCell<T> isn’tSync, and ifArc<T> was alwaysSend,Arc<RefCell<T>> would be as well. But then we’d have a problem:RefCell<T> is not thread safe; it keeps track of the borrowing count usingnon-atomic operations.

In the end, this means that you may need to pairArc<T> with some sort ofstd::sync type, usuallyMutex<T>.

§Breaking cycles withWeak

Thedowngrade method can be used to create a non-owningWeak pointer. AWeak pointer can beupgradedto anArc, but this will returnNone if the value stored in the allocation hasalready been dropped. In other words,Weak pointers do not keep the valueinside the allocation alive; however, theydo keep the allocation(the backing store for the value) alive.

A cycle betweenArc pointers will never be deallocated. For this reason,Weak is used to break cycles. For example, a tree could havestrongArc pointers from parent nodes to children, andWeakpointers from children back to their parents.

§Cloning references

Creating a new reference from an existing reference-counted pointer is done using theClone trait implemented forArc<T> andWeak<T>.

usestd::sync::Arc;letfoo = Arc::new(vec![1.0,2.0,3.0]);// The two syntaxes below are equivalent.leta = foo.clone();letb = Arc::clone(&foo);// a, b, and foo are all Arcs that point to the same memory location

§Deref behavior

Arc<T> automatically dereferences toT (via theDeref trait),so you can callT’s methods on a value of typeArc<T>. To avoid nameclashes withT’s methods, the methods ofArc<T> itself are associatedfunctions, called usingfully qualified syntax:

usestd::sync::Arc;letmy_arc = Arc::new(());letmy_weak = Arc::downgrade(&my_arc);

Arc<T>’s implementations of traits likeClone may also be called usingfully qualified syntax. Some people prefer to use fully qualified syntax,while others prefer using method-call syntax.

usestd::sync::Arc;letarc = Arc::new(());// Method-call syntaxletarc2 = arc.clone();// Fully qualified syntaxletarc3 = Arc::clone(&arc);

Weak<T> does not auto-dereference toT, because the inner value may havealready been dropped.

§Examples

Sharing some immutable data between threads:

usestd::sync::Arc;usestd::thread;letfive = Arc::new(5);for _ in0..10{letfive = Arc::clone(&five);    thread::spawn(move|| {println!("{five:?}");    });}

Sharing a mutableAtomicUsize:

usestd::sync::Arc;usestd::sync::atomic::{AtomicUsize, Ordering};usestd::thread;letval = Arc::new(AtomicUsize::new(5));for _ in0..10{letval = Arc::clone(&val);    thread::spawn(move|| {letv = val.fetch_add(1, Ordering::Relaxed);println!("{v:?}");    });}

See therc documentation for more examples of referencecounting in general.

Implementations§

Source§

impl<T>Arc<T>

1.0.0 ·Source

pub fnnew(data: T) ->Arc<T>

Constructs a newArc<T>.

§Examples
usestd::sync::Arc;letfive = Arc::new(5);
1.60.0 ·Source

pub fnnew_cyclic<F>(data_fn: F) ->Arc<T>
where F:FnOnce(&Weak<T>) -> T,

Constructs a newArc<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 theArc<T> is created, such that you canclone and store it inside theT.

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

Since the newArc<T> is not fully-constructed untilArc<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.

§Example
usestd::sync::{Arc, Weak};structGadget {    me: Weak<Gadget>,}implGadget {/// Constructs a reference counted Gadget.fnnew() -> Arc<Self> {// `me` is a `Weak<Gadget>` pointing at the new allocation of the        // `Arc` we're constructing.Arc::new_cyclic(|me| {// Create the actual struct here.Gadget { me: me.clone() }        })    }/// Returns a reference counted pointer to Self.fnme(&self) -> Arc<Self> {self.me.upgrade().unwrap()    }}
1.82.0 ·Source

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

Constructs a newArc with uninitialized contents.

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

pub fnnew_zeroed() ->Arc<MaybeUninit<T>>

Constructs a newArc with uninitialized contents, with the memorybeing filled with0 bytes.

SeeMaybeUninit::zeroed for examples of correct and incorrect usageof this method.

§Examples
usestd::sync::Arc;letzero = Arc::<u32>::new_zeroed();letzero =unsafe{ zero.assume_init() };assert_eq!(*zero,0)
1.33.0 ·Source

pub fnpin(data: T) ->Pin<Arc<T>>

Constructs a newPin<Arc<T>>. IfT does not implementUnpin, thendata will be pinned in memory and unable to be moved.

Source

pub fntry_pin(data: T) ->Result<Pin<Arc<T>>,AllocError>

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

Constructs a newPin<Arc<T>>, return an error if allocation fails.

Source

pub fntry_new(data: T) ->Result<Arc<T>,AllocError>

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

Constructs a newArc<T>, returning an error if allocation fails.

§Examples
#![feature(allocator_api)]usestd::sync::Arc;letfive = Arc::try_new(5)?;
Source

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

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

Constructs a newArc with uninitialized contents, returning an errorif allocation fails.

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

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

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

Constructs a newArc with uninitialized contents, with the memorybeing filled with0 bytes, returning an error if allocation fails.

SeeMaybeUninit::zeroed for examples of correct and incorrect usageof this method.

§Examples
#![feature( allocator_api)]usestd::sync::Arc;letzero = Arc::<u32>::try_new_zeroed()?;letzero =unsafe{ zero.assume_init() };assert_eq!(*zero,0);
Source

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

🔬This is a nightly-only experimental API. (smart_pointer_try_map #144419)

Maps the value in anArc, reusing the allocation if possible.

f is called on a reference to the value in theArc, and the result is returned, also inanArc.

Note: this is an associated function, which means that you haveto call it asArc::map(a, f) instead ofr.map(a). Thisis so that there is no conflict with a method on the inner type.

§Examples
#![feature(smart_pointer_try_map)]usestd::sync::Arc;letr = Arc::new(7);letnew = Arc::map(r, |i| i +7);assert_eq!(*new,14);
Source

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

🔬This is a nightly-only experimental API. (smart_pointer_try_map #144419)

Attempts to map the value in anArc, reusing the allocation if possible.

f is called on a reference to the value in theArc, and if the operation succeeds, theresult is returned, also in anArc.

Note: this is an associated function, which means that you haveto call it asArc::try_map(a, f) instead ofa.try_map(f). Thisis so that there is no conflict with a method on the inner type.

§Examples
#![feature(smart_pointer_try_map)]usestd::sync::Arc;letb = Arc::new(7);letnew = Arc::try_map(b, |&i| u32::try_from(i)).unwrap();assert_eq!(*new,7);
Source§

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

Source

pub fnnew_in(data: T, alloc: A) ->Arc<T, A>

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

Constructs a newArc<T> in the provided allocator.

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

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

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

Constructs a newArc with uninitialized contents in the provided allocator.

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

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

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

Constructs a newArc with uninitialized contents, with the memorybeing filled with0 bytes, in the provided allocator.

SeeMaybeUninit::zeroed for examples of correct and incorrect usageof this method.

§Examples
#![feature(allocator_api)]usestd::sync::Arc;usestd::alloc::System;letzero = Arc::<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) ->Arc<T, A>
where F:FnOnce(&Weak<T, A>) -> T,

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

Constructs a newArc<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 theArc<T, A> is created, such that you canclone and store it inside theT.

new_cyclic_in first allocates the managed allocation for theArc<T, A>,then calls your closure, giving it aWeak<T, A> to this allocation,and only afterwards completes the construction of theArc<T, A> by placingtheT returned from your closure into the allocation.

Since the newArc<T, A> is not fully-constructed untilArc<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> is dropped normally.

§Example

Seenew_cyclic

Source

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

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

Constructs a newPin<Arc<T, A>> in the provided allocator. IfT does not implementUnpin,thendata will be pinned in memory and unable to be moved.

Source

pub fntry_pin_in(data: T, alloc: A) ->Result<Pin<Arc<T, A>>,AllocError>
where A: 'static,

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

Constructs a newPin<Arc<T, A>> in the provided allocator, return an error if allocationfails.

Source

pub fntry_new_in(data: T, alloc: A) ->Result<Arc<T, A>,AllocError>

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

Constructs a newArc<T, A> in the provided allocator, returning an error if allocation fails.

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

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

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

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

§Examples
#![feature(allocator_api)]#![feature(get_mut_unchecked)]usestd::sync::Arc;usestd::alloc::System;letmutfive = Arc::<u32,_>::try_new_uninit_in(System)?;letfive =unsafe{// Deferred initialization:Arc::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<Arc<MaybeUninit<T>, A>,AllocError>

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

Constructs a newArc with uninitialized contents, with the memorybeing filled with0 bytes, in the provided allocator, returning an error if allocationfails.

SeeMaybeUninit::zeroed for examples of correct and incorrect usageof this method.

§Examples
#![feature(allocator_api)]usestd::sync::Arc;usestd::alloc::System;letzero = Arc::<u32,_>::try_new_zeroed_in(System)?;letzero =unsafe{ zero.assume_init() };assert_eq!(*zero,0);
1.4.0 ·Source

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

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

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

This will succeed even if there are outstanding weak references.

It is strongly recommended to useArc::into_inner instead if you don’tkeep theArc in theErr case.Immediately dropping theErr-value, as the expressionArc::try_unwrap(this).ok() does, can cause the strong count todrop to zero and the inner value of theArc to be dropped.For instance, if two threads execute such an expression in parallel,there is a race condition without the possibility of unsafety:The threads could first both check whether they own the last instanceinArc::try_unwrap, determine that they both do not, and then bothdiscard and drop their instance in the call took.In this scenario, the value inside theArc is safely destroyedby exactly one of the threads, but neither thread will ever be ableto use the value.

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

pub fninto_inner(this:Arc<T, A>) ->Option<T>

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

Otherwise,None is returned and theArc is dropped.

This will succeed even if there are outstanding weak references.

IfArc::into_inner is called on every clone of thisArc,it is guaranteed that exactly one of the calls returns the inner value.This means in particular that the inner value is not dropped.

Arc::try_unwrap is conceptually similar toArc::into_inner, but itis meant for different use-cases. If used as a direct replacementforArc::into_inner anyway, such as with the expressionArc::try_unwrap(this).ok(), then it doesnot give the same guarantee as described in the previous paragraph.For more information, see the examples below and read the documentationofArc::try_unwrap.

§Examples

Minimal example demonstrating the guarantee thatArc::into_inner gives.

usestd::sync::Arc;letx = Arc::new(3);lety = Arc::clone(&x);// Two threads calling `Arc::into_inner` on both clones of an `Arc`:letx_thread = std::thread::spawn(|| Arc::into_inner(x));lety_thread = std::thread::spawn(|| Arc::into_inner(y));letx_inner_value = x_thread.join().unwrap();lety_inner_value = y_thread.join().unwrap();// One of the threads is guaranteed to receive the inner value:assert!(matches!(    (x_inner_value, y_inner_value),    (None,Some(3)) | (Some(3),None)));// The result could also be `(None, None)` if the threads called// `Arc::try_unwrap(x).ok()` and `Arc::try_unwrap(y).ok()` instead.

A more practical example demonstrating the need forArc::into_inner:

usestd::sync::Arc;// Definition of a simple singly linked list using `Arc`:#[derive(Clone)]structLinkedList<T>(Option<Arc<Node<T>>>);structNode<T>(T,Option<Arc<Node<T>>>);// Dropping a long `LinkedList<T>` relying on the destructor of `Arc`// can cause a stack overflow. To prevent this, we can provide a// manual `Drop` implementation that does the destruction in a loop:impl<T> DropforLinkedList<T> {fndrop(&mutself) {letmutlink =self.0.take();while letSome(arc_node) = link.take() {if letSome(Node(_value, next)) = Arc::into_inner(arc_node) {                link = next;            }        }    }}// Implementation of `new` and `push` omittedimpl<T> LinkedList<T> {/* ... */}// The following code could have still caused a stack overflow// despite the manual `Drop` impl if that `Drop` impl had used// `Arc::try_unwrap(arc).ok()` instead of `Arc::into_inner(arc)`.// Create a long list and clone itletmutx = LinkedList::new();letsize =100000;foriin0..size {    x.push(i);// Adds i to the front of x}lety = x.clone();// Drop the clones in parallelletx_thread = std::thread::spawn(|| drop(x));lety_thread = std::thread::spawn(|| drop(y));x_thread.join().unwrap();y_thread.join().unwrap();
Source§

impl<T>Arc<[T]>

1.82.0 ·Source

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

Constructs a new atomically reference-counted slice with uninitialized contents.

§Examples
usestd::sync::Arc;letmutvalues = Arc::<[u32]>::new_uninit_slice(3);// Deferred initialization:letdata = Arc::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) ->Arc<[MaybeUninit<T>]>

Constructs a new atomically 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::sync::Arc;letvalues = Arc::<[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<Arc<[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>Arc<[T], A>
where A:Allocator,

Source

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

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

Constructs a new atomically reference-counted slice with uninitialized contents in theprovided allocator.

§Examples
#![feature(get_mut_unchecked)]#![feature(allocator_api)]usestd::sync::Arc;usestd::alloc::System;letmutvalues = Arc::<[u32],_>::new_uninit_slice_in(3, System);letvalues =unsafe{// Deferred initialization:Arc::get_mut_unchecked(&mutvalues)[0].as_mut_ptr().write(1);    Arc::get_mut_unchecked(&mutvalues)[1].as_mut_ptr().write(2);    Arc::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) ->Arc<[MaybeUninit<T>], A>

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

Constructs a new atomically reference-counted slice with uninitialized contents, with the memory beingfilled with0 bytes, in the provided allocator.

SeeMaybeUninit::zeroed for examples of correct andincorrect usage of this method.

§Examples
#![feature(allocator_api)]usestd::sync::Arc;usestd::alloc::System;letvalues = Arc::<[u32],_>::new_zeroed_slice_in(3, System);letvalues =unsafe{ values.assume_init() };assert_eq!(*values, [0,0,0])
Source§

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

1.82.0 ·Source

pub unsafe fnassume_init(self) ->Arc<T, A>

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

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

Source

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

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

Constructs a newArc<T> with a clone ofvalue.

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

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

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

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

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

impl<T, A>Arc<T, A>

Source

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

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

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

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

pub fntry_clone_from_ref_in( value:&T, alloc: A,) ->Result<Arc<T, A>,AllocError>

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

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

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

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

1.82.0 ·Source

pub unsafe fnassume_init(self) ->Arc<[T], A>

Converts toArc<[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::sync::Arc;letmutvalues = Arc::<[u32]>::new_uninit_slice(3);// Deferred initialization:letdata = Arc::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>Arc<T>
where T: ?Sized,

1.17.0 ·Source

pub unsafe fnfrom_raw(ptr:*const T) ->Arc<T>

Constructs anArc<T> from a raw pointer.

The raw pointer must have been previously returned by a call toArc<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 ifArc<U> was constructedthroughArc<T> and then converted toArc<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 returnedArc<T> is never accessed.

§Examples
usestd::sync::Arc;letx = Arc::new("hello".to_owned());letx_ptr = Arc::into_raw(x);unsafe{// Convert back to an `Arc` to prevent leak.letx = Arc::from_raw(x_ptr);assert_eq!(&*x,"hello");// Further calls to `Arc::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::sync::Arc;letx: Arc<[u32]> = Arc::new([1,2,3]);letx_ptr:*const[u32] = Arc::into_raw(x);unsafe{letx: Arc<[u32;3]> = Arc::from_raw(x_ptr.cast::<[u32;3]>());assert_eq!(&*x,&[1,2,3]);}
1.17.0 ·Source

pub fninto_raw(this:Arc<T>) ->*const T

Consumes theArc, returning the wrapped pointer.

To avoid a memory leak the pointer must be converted back to anArc usingArc::from_raw.

§Examples
usestd::sync::Arc;letx = Arc::new("hello".to_owned());letx_ptr = Arc::into_raw(x);assert_eq!(unsafe{&*x_ptr },"hello");
1.51.0 ·Source

pub unsafe fnincrement_strong_count(ptr:*const T)

Increments the strong reference count on theArc<T> associated with theprovided pointer by one.

§Safety

The pointer must have been obtained throughArc::into_raw and must satisfy thesame layout requirements specified inArc::from_raw_in.The associatedArc 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::sync::Arc;letfive = Arc::new(5);unsafe{letptr = Arc::into_raw(five);    Arc::increment_strong_count(ptr);// This assertion is deterministic because we haven't shared    // the `Arc` between threads.letfive = Arc::from_raw(ptr);assert_eq!(2, Arc::strong_count(&five));}
1.51.0 ·Source

pub unsafe fndecrement_strong_count(ptr:*const T)

Decrements the strong reference count on theArc<T> associated with theprovided pointer by one.

§Safety

The pointer must have been obtained throughArc::into_raw and must satisfy thesame layout requirements specified inArc::from_raw_in.The associatedArc 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 finalArc and backing storage, butshould not be called after the finalArc has beenreleased.

§Examples
usestd::sync::Arc;letfive = Arc::new(5);unsafe{letptr = Arc::into_raw(five);    Arc::increment_strong_count(ptr);// Those assertions are deterministic because we haven't shared    // the `Arc` between threads.letfive = Arc::from_raw(ptr);assert_eq!(2, Arc::strong_count(&five));    Arc::decrement_strong_count(ptr);assert_eq!(1, Arc::strong_count(&five));}
Source§

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

Source

pub fnallocator(this: &Arc<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 asArc::allocator(&a) instead ofa.allocator(). Thisis so that there is no conflict with a method on the inner type.

Source

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

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

Consumes theArc, returning the wrapped pointer and allocator.

To avoid a memory leak the pointer must be converted back to anArc usingArc::from_raw_in.

§Examples
#![feature(allocator_api)]usestd::sync::Arc;usestd::alloc::System;letx = Arc::new_in("hello".to_owned(), System);let(ptr, alloc) = Arc::into_raw_with_allocator(x);assert_eq!(unsafe{&*ptr },"hello");letx =unsafe{ Arc::from_raw_in(ptr, alloc) };assert_eq!(&*x,"hello");
1.45.0 ·Source

pub fnas_ptr(this: &Arc<T, A>) ->*const T

Provides a raw pointer to the data.

The counts are not affected in any way and theArc is not consumed. The pointer is valid foras long as there are strong counts in theArc.

§Examples
usestd::sync::Arc;letx = Arc::new("hello".to_owned());lety = Arc::clone(&x);letx_ptr = Arc::as_ptr(&x);assert_eq!(x_ptr, Arc::as_ptr(&y));assert_eq!(unsafe{&*x_ptr },"hello");
Source

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

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

Constructs anArc<T, A> from a raw pointer.

The raw pointer must have been previously returned by a call toArc<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 ifArc<U> was constructedthroughArc<T> and then converted toArc<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 returnedArc<T> is never accessed.

§Examples
#![feature(allocator_api)]usestd::sync::Arc;usestd::alloc::System;letx = Arc::new_in("hello".to_owned(), System);let(x_ptr, alloc) = Arc::into_raw_with_allocator(x);unsafe{// Convert back to an `Arc` to prevent leak.letx = Arc::from_raw_in(x_ptr, System);assert_eq!(&*x,"hello");// Further calls to `Arc::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::sync::Arc;usestd::alloc::System;letx: Arc<[u32],_> = Arc::new_in([1,2,3], System);letx_ptr:*const[u32] = Arc::into_raw_with_allocator(x).0;unsafe{letx: Arc<[u32;3],_> = Arc::from_raw_in(x_ptr.cast::<[u32;3]>(), System);assert_eq!(&*x,&[1,2,3]);}
1.4.0 ·Source

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

Creates a newWeak pointer to this allocation.

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

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

Gets the number ofWeak pointers to this allocation.

§Safety

This method by itself is safe, but using it correctly requires extra care.Another thread can change the weak count at any time,including potentially between calling this method and acting on the result.

§Examples
usestd::sync::Arc;letfive = Arc::new(5);let_weak_five = Arc::downgrade(&five);// This assertion is deterministic because we haven't shared// the `Arc` or `Weak` between threads.assert_eq!(1, Arc::weak_count(&five));
1.15.0 ·Source

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

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

§Safety

This method by itself is safe, but using it correctly requires extra care.Another thread can change the strong count at any time,including potentially between calling this method and acting on the result.

§Examples
usestd::sync::Arc;letfive = Arc::new(5);let_also_five = Arc::clone(&five);// This assertion is deterministic because we haven't shared// the `Arc` between threads.assert_eq!(2, Arc::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 theArc<T> associated with theprovided pointer by one.

§Safety

The pointer must have been obtained throughArc::into_raw and must satisfy thesame layout requirements specified inArc::from_raw_in.The associatedArc 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::sync::Arc;usestd::alloc::System;letfive = Arc::new_in(5, System);unsafe{let(ptr, _alloc) = Arc::into_raw_with_allocator(five);    Arc::increment_strong_count_in(ptr, System);// This assertion is deterministic because we haven't shared    // the `Arc` between threads.letfive = Arc::from_raw_in(ptr, System);assert_eq!(2, Arc::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 theArc<T> associated with theprovided pointer by one.

§Safety

The pointer must have been obtained throughArc::into_raw and must satisfy thesame layout requirements specified inArc::from_raw_in.The associatedArc 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 finalArc and backing storage, butshould not be called after the finalArc has beenreleased.

§Examples
#![feature(allocator_api)]usestd::sync::Arc;usestd::alloc::System;letfive = Arc::new_in(5, System);unsafe{let(ptr, _alloc) = Arc::into_raw_with_allocator(five);    Arc::increment_strong_count_in(ptr, System);// Those assertions are deterministic because we haven't shared    // the `Arc` between threads.letfive = Arc::from_raw_in(ptr, System);assert_eq!(2, Arc::strong_count(&five));    Arc::decrement_strong_count_in(ptr, System);assert_eq!(1, Arc::strong_count(&five));}
1.17.0 ·Source

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

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

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

impl<T, A>Arc<T, A>

1.4.0 ·Source

pub fnmake_mut(this: &mutArc<T, A>) ->&mut T

Makes a mutable reference into the givenArc.

If there are otherArc 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 otherArc pointers to this allocation, but someWeakpointers, then theWeak pointers will be dissociated and the inner value will notbe cloned.

See alsoget_mut, which will fail rather than cloning the inner valueor dissociatingWeak pointers.

§Examples
usestd::sync::Arc;letmutdata = Arc::new(5);*Arc::make_mut(&mutdata) +=1;// Won't clone anythingletmutother_data = Arc::clone(&data);// Won't clone inner data*Arc::make_mut(&mutdata) +=1;// Clones inner data*Arc::make_mut(&mutdata) +=1;// Won't clone anything*Arc::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 dissociated:

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

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

1.76.0 ·Source

pub fnunwrap_or_clone(this:Arc<T, A>) -> T

If we have the only reference toT then unwrap it. Otherwise, cloneT and return theclone.

Assumingarc_t is of typeArc<T>, this function is functionally equivalent to(*arc_t).clone(), but will avoid cloning the inner value where possible.

§Examples
letinner = String::from("test");letptr = inner.as_ptr();letarc = Arc::new(inner);letinner = Arc::unwrap_or_clone(arc);// The inner value was not clonedassert!(ptr::eq(ptr, inner.as_ptr()));letarc = Arc::new(inner);letarc2 = arc.clone();letinner = Arc::unwrap_or_clone(arc);// Because there were 2 references, we had to clone the inner value.assert!(!ptr::eq(ptr, inner.as_ptr()));// `arc2` is the last reference, so when we unwrap it we get back// the original `String`.letinner = Arc::unwrap_or_clone(arc2);assert!(ptr::eq(ptr, inner.as_ptr()));
Source§

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

1.4.0 ·Source

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

Returns a mutable reference into the givenArc, if there areno otherArc 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 otherArc pointers.

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

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

🔬This is a nightly-only experimental API. (get_mut_unchecked #63292)

Returns a mutable reference into the givenArc,without any check.

See alsoget_mut, which is safe and does appropriate checks.

§Safety

If any otherArc 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 Arc (including lifetimes). This is trivially the case if nosuch pointers exist, for example immediately afterArc::new.

§Examples
#![feature(get_mut_unchecked)]usestd::sync::Arc;letmutx = Arc::new(String::new());unsafe{    Arc::get_mut_unchecked(&mutx).push_str("foo")}assert_eq!(*x,"foo");

OtherArc pointers to the same allocation must be to the same type.

#![feature(get_mut_unchecked)]usestd::sync::Arc;letx: Arc<str> = Arc::from("Hello, world!");letmuty: Arc<[u8]> = x.clone().into();unsafe{// this is Undefined Behavior, because x's inner type is str, not [u8]Arc::get_mut_unchecked(&muty).fill(0xff);// 0xff is invalid in UTF-8}println!("{}",&*x);// Invalid UTF-8 in a str

OtherArc pointers to the same allocation must be to the exact same type, including lifetimes.

#![feature(get_mut_unchecked)]usestd::sync::Arc;letx: Arc<&str> = Arc::new("Hello, world!");{lets = String::from("Oh, no!");letmuty: Arc<&str> = x.clone();unsafe{// this is Undefined Behavior, because x's inner type        // is &'long str, not &'short str*Arc::get_mut_unchecked(&muty) =&s;    }}println!("{}",&*x);// Use-after-free
Source

pub fnis_unique(this: &Arc<T, A>) ->bool

🔬This is a nightly-only experimental API. (arc_is_unique #138938)

Determine whether this is the unique reference to the underlying data.

Returnstrue if there are no otherArc orWeak pointers to the same allocation;returnsfalse otherwise.

If this function returnstrue, then is guaranteed to be safe to callget_mut_uncheckedon thisArc, so long as no clones occur in between.

§Examples
#![feature(arc_is_unique)]usestd::sync::Arc;letx = Arc::new(3);assert!(Arc::is_unique(&x));lety = Arc::clone(&x);assert!(!Arc::is_unique(&x));drop(y);// Weak references also count, because they could be upgraded at any time.letz = Arc::downgrade(&x);assert!(!Arc::is_unique(&x));
§Pointer invalidation

This function will always return the same value asArc::get_mut(arc).is_some(). However,unlike that operation it does not produce any mutable references to the underlying data,meaning no pointers to the data inside theArc are invalidated by the call. Thus, thefollowing code is valid, even though it would be UB if it usedArc::get_mut:

#![feature(arc_is_unique)]usestd::sync::Arc;letarc = Arc::new(5);letpointer:*consti32 =&*arc;assert!(Arc::is_unique(&arc));assert_eq!(unsafe{*pointer },5);
§Atomic orderings

Concurrent drops to otherArc pointers to the same allocation will synchronize with thiscall - that is, this call performs anAcquire operation on the underlying strong and weakref counts. This ensures that callingget_mut_unchecked is safe.

Note that this operation requires locking the weak ref count, so concurrent calls todowngrade may spin-loop for a short period of time.

Source§

impl<A>Arc<dynAny +Sync +Send, A>
where A:Allocator,

1.29.0 ·Source

pub fndowncast<T>(self) ->Result<Arc<T, A>,Arc<dynAny +Sync +Send, A>>
where T:Any +Send +Sync,

Attempts to downcast theArc<dyn Any + Send + Sync> to a concrete type.

§Examples
usestd::any::Any;usestd::sync::Arc;fnprint_if_string(value: Arc<dynAny + Send + Sync>) {if letOk(string) = value.downcast::<String>() {println!("String ({}): {}", string.len(), string);    }}letmy_string ="Hello World".to_string();print_if_string(Arc::new(my_string));print_if_string(Arc::new(0i8));
Source

pub unsafe fndowncast_unchecked<T>(self) ->Arc<T, A>
where T:Any +Send +Sync,

🔬This is a nightly-only experimental API. (downcast_unchecked #90850)

Downcasts theArc<dyn Any + Send + Sync> to a concrete type.

For a safe alternative seedowncast.

§Examples
#![feature(downcast_unchecked)]usestd::any::Any;usestd::sync::Arc;letx: Arc<dynAny + Send + Sync> = Arc::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 forArc<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.64.0 ·Source§

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

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

This impl allows implementing traits that requireAsFd on Arc.

usestd::net::UdpSocket;usestd::sync::Arc;traitMyTrait: AsFd {}implMyTraitforArc<UdpSocket> {}implMyTraitforBox<UdpSocket> {}
Source§

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

Borrows the file descriptor.Read more
1.71.0 ·Source§

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

Available onWindows only.

This impl allows implementing traits that requireAsHandle on Arc.

usestd::fs::File;usestd::sync::Arc;traitMyTrait: AsHandle {}implMyTraitforArc<File> {}implMyTraitforBox<File> {}
Source§

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

Borrows the handle.Read more
1.63.0 ·Source§

impl<T:AsRawFd>AsRawFd forArc<T>

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

This impl allows implementing traits that requireAsRawFd on Arc.

usestd::net::UdpSocket;usestd::sync::Arc;traitMyTrait: AsRawFd {}implMyTraitforArc<UdpSocket> {}implMyTraitforBox<UdpSocket> {}
Source§

fnas_raw_fd(&self) ->RawFd

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

impl<T, A>AsRef<T> forArc<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 forArc<T>

Available onWindows only.

This impl allows implementing traits that requireAsSocket on Arc.

usestd::net::UdpSocket;usestd::sync::Arc;traitMyTrait: AsSocket {}implMyTraitforArc<UdpSocket> {}implMyTraitforBox<UdpSocket> {}
Source§

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

Borrows the socket.
1.0.0 ·Source§

impl<T, A>Borrow<T> forArc<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 forArc<T, A>
where A:Allocator +Clone, T: ?Sized,

Source§

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

Makes a clone of theArc pointer.

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

§Examples
usestd::sync::Arc;letfive = Arc::new(5);let _= Arc::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 forArc<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.80.0 ·Source§

impl<T>Default forArc<[T]>

Source§

fndefault() ->Arc<[T]>

Creates an empty[T] inside an Arc

This may or may not share an allocation with other Arcs.

1.80.0 ·Source§

implDefault forArc<CStr>

Source§

fndefault() ->Arc<CStr>

Creates an empty CStr inside an Arc

This may or may not share an allocation with other Arcs.

1.0.0 ·Source§

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

Source§

fndefault() ->Arc<T>

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

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

implDefault forArc<str>

Source§

fndefault() ->Arc<str>

Creates an empty str inside an Arc

This may or may not share an allocation with other Arcs.

1.91.0 ·Source§

impl<T>Default forPin<Arc<T>>
whereArc<T>:Default, T: ?Sized,

Source§

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

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

impl<T, A>Deref forArc<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 forArc<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 forArc<T, A>
where A:Allocator, T: ?Sized,

Source§

fndrop(&mut self)

Drops theArc.

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::sync::Arc;structFoo;implDropforFoo {fndrop(&mutself) {println!("dropped!");    }}letfoo  = Arc::new(Foo);letfoo2 = Arc::clone(&foo);drop(foo);// Doesn't print anythingdrop(foo2);// Prints "dropped!"
1.52.0 ·Source§

impl<T>Error forArc<T>
where T:Error + ?Sized,

Source§

fncause(&self) ->Option<&dynError>

👎Deprecated since 1.33.0: replaced by Error::source, which can support downcasting
Source§

fnsource(&self) ->Option<&(dynError + 'static)>

Returns the lower-level source of this error, if any.Read more
Source§

fnprovide<'a>(&'a self, req: &mutRequest<'a>)

🔬This is a nightly-only experimental API. (error_generic_member_access #99301)
Provides type-based access to context intended for error reports.Read more
1.0.0 ·Source§

fndescription(&self) -> &str

👎Deprecated since 1.42.0: use the Display impl or to_string()
1.21.0 ·Source§

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

Source§

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

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

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

implFrom<&CStr> forArc<CStr>

Available ontarget_has_atomic=ptr only.
Source§

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

Converts a&CStr into aArc<CStr>,by copying the contents into a newly allocatedArc.

1.24.0 ·Source§

implFrom<&OsStr> forArc<OsStr>

Source§

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

Copies the string into a newly allocatedArc<OsStr>.

1.24.0 ·Source§

implFrom<&Path> forArc<Path>

Source§

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

Converts aPath into anArc by copying thePath data into a newArc buffer.

1.84.0 ·Source§

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

Source§

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

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

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

implFrom<&mutCStr> forArc<CStr>

Available ontarget_has_atomic=ptr only.
Source§

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

Converts a&mut CStr into aArc<CStr>,by copying the contents into a newly allocatedArc.

1.84.0 ·Source§

implFrom<&mutOsStr> forArc<OsStr>

Source§

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

Copies the string into a newly allocatedArc<OsStr>.

1.84.0 ·Source§

implFrom<&mutPath> forArc<Path>

Source§

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

Converts aPath into anArc by copying thePath data into a newArc buffer.

1.84.0 ·Source§

implFrom<&mutstr> forArc<str>

Source§

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

Allocates a reference-countedstr and copiesv into it.

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

implFrom<&str> forArc<str>

Source§

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

Allocates a reference-countedstr and copiesv into it.

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

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

Source§

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

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

The conversion moves the array into a newly allocatedArc.

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

implFrom<Arc<[u8]>> forArc<ByteStr>

Available onnon-no_rc and non-no_sync andtarget_has_atomic=ptr only.
Source§

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

Converts to this type from the input type.
Source§

implFrom<Arc<ByteStr>> forArc<[u8]>

Available onnon-no_rc and non-no_sync andtarget_has_atomic=ptr only.
Source§

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

Converts to this type from the input type.
1.51.0 ·Source§

impl<W>From<Arc<W>> forRawWaker
where W:Wake +Send +Sync + 'static,

Available ontarget_has_atomic=ptr only.
Source§

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

Use aWake-able type as aRawWaker.

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

1.51.0 ·Source§

impl<W>From<Arc<W>> forWaker
where W:Wake +Send +Sync + 'static,

Available ontarget_has_atomic=ptr only.
Source§

fnfrom(waker:Arc<W>) ->Waker

Use aWake-able type as aWaker.

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

1.62.0 ·Source§

implFrom<Arc<str>> forArc<[u8]>

Source§

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

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

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

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

Source§

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

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

§Example
letunique: Box<str> = Box::from("eggplant");letshared: Arc<str> = Arc::from(unique);assert_eq!("eggplant",&shared[..]);
1.24.0 ·Source§

implFrom<CString> forArc<CStr>

Available ontarget_has_atomic=ptr only.
Source§

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

Converts aCString into anArc<CStr> by moving theCStringdata into a newArc buffer.

1.45.0 ·Source§

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

Source§

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

Creates an atomically reference-counted pointer from a clone-on-writepointer by copying its content.

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

implFrom<OsString> forArc<OsStr>

Source§

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

Converts anOsString into anArc<OsStr> by moving theOsStringdata into a newArc buffer.

1.24.0 ·Source§

implFrom<PathBuf> forArc<Path>

Source§

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

Converts aPathBuf into anArc<Path> by moving thePathBuf datainto a newArc buffer.

1.21.0 ·Source§

implFrom<String> forArc<str>

Source§

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

Allocates a reference-countedstr and copiesv into it.

§Example
letunique: String ="eggplant".to_owned();letshared: Arc<str> = Arc::from(unique);assert_eq!("eggplant",&shared[..]);
1.6.0 ·Source§

impl<T>From<T> forArc<T>

Source§

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

Converts aT into anArc<T>

The conversion moves the value into anewly allocatedArc. It is equivalent tocallingArc::new(t).

§Example
letx =5;letarc = Arc::new(5);assert_eq!(Arc::from(x), arc);
1.21.0 ·Source§

impl<T, A>From<Vec<T, A>> forArc<[T], A>
where A:Allocator +Clone,

Source§

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

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

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

impl<T>FromIterator<T> forArc<[T]>

Source§

fnfrom_iter<I>(iter: I) ->Arc<[T]>
where I:IntoIterator<Item = T>,

Takes each element in theIterator and collects it into anArc<[T]>.

§Performance characteristics
§The general case

In the general case, collecting intoArc<[T]> is done by firstcollecting into aVec<T>. That is, when writing the following:

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

this behaves as if we wrote:

letevens: Arc<[u8]> = (0..10).filter(|&x| x %2==0)    .collect::<Vec<_>>()// The first set of allocations happens here..into();// A second allocation for `Arc<[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 theArc<[T]>.

§Iterators of known length

When yourIterator implementsTrustedLen and is of an exact size,a single allocation will be made for theArc<[T]>. For example:

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

impl<T, A>Hash forArc<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 forArc<T, A>
where T:Ord + ?Sized, A:Allocator,

Source§

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

Comparison for twoArcs.

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

§Examples
usestd::sync::Arc;usestd::cmp::Ordering;letfive = Arc::new(5);assert_eq!(Ordering::Less, five.cmp(&Arc::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 forArc<T, A>
where T:PartialEq + ?Sized, A:Allocator,

Source§

fneq(&self, other: &Arc<T, A>) ->bool

Equality for twoArcs.

TwoArcs are equal if their inner values are equal, even if they arestored in different allocation.

IfT also implementsEq (implying reflexivity of equality),twoArcs that point to the same allocation are always equal.

§Examples
usestd::sync::Arc;letfive = Arc::new(5);assert!(five == Arc::new(5));
Source§

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

Inequality for twoArcs.

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

IfT also implementsEq (implying reflexivity of equality),twoArcs that point to the same value are always equal.

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

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

Source§

fnpartial_cmp(&self, other: &Arc<T, A>) ->Option<Ordering>

Partial comparison for twoArcs.

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

§Examples
usestd::sync::Arc;usestd::cmp::Ordering;letfive = Arc::new(5);assert_eq!(Some(Ordering::Less), five.partial_cmp(&Arc::new(6)));
Source§

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

Less-than comparison for twoArcs.

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

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

fnle(&self, other: &Arc<T, A>) ->bool

‘Less than or equal to’ comparison for twoArcs.

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

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

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

Greater-than comparison for twoArcs.

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

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

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

‘Greater than or equal to’ comparison for twoArcs.

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

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

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

Source§

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

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

implRead forArc<File>

Source§

fnread(&mut self, buf: &mut [u8]) ->Result<usize>

Pull some bytes from this source into the specified buffer, returninghow many bytes were read.Read more
Source§

fnread_vectored(&mut self, bufs: &mut [IoSliceMut<'_>]) ->Result<usize>

Likeread, except that it reads into a slice of buffers.Read more
Source§

fnread_buf(&mut self, cursor:BorrowedCursor<'_>) ->Result<()>

🔬This is a nightly-only experimental API. (read_buf #78485)
Pull some bytes from this source into the specified buffer.Read more
Source§

fnis_read_vectored(&self) ->bool

🔬This is a nightly-only experimental API. (can_vector #69941)
Determines if thisReader has an efficientread_vectoredimplementation.Read more
Source§

fnread_to_end(&mut self, buf: &mutVec<u8>) ->Result<usize>

Reads all bytes until EOF in this source, placing them intobuf.Read more
Source§

fnread_to_string(&mut self, buf: &mutString) ->Result<usize>

Reads all bytes until EOF in this source, appending them tobuf.Read more
1.6.0 ·Source§

fnread_exact(&mut self, buf: &mut [u8]) ->Result<()>

Reads the exact number of bytes required to fillbuf.Read more
Source§

fnread_buf_exact(&mut self, cursor:BorrowedCursor<'_>) ->Result<()>

🔬This is a nightly-only experimental API. (read_buf #78485)
Reads the exact number of bytes required to fillcursor.Read more
1.0.0 ·Source§

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

Creates a “by reference” adapter for this instance ofRead.Read more
1.0.0 ·Source§

fnbytes(self) ->Bytes<Self>
where Self:Sized,

Transforms thisRead instance to anIterator over its bytes.Read more
1.0.0 ·Source§

fnchain<R:Read>(self, next: R) ->Chain<Self, R>
where Self:Sized,

Creates an adapter which will chain this stream with another.Read more
1.0.0 ·Source§

fntake(self, limit:u64) ->Take<Self>
where Self:Sized,

Creates an adapter which will read at mostlimit bytes from it.Read more
Source§

fnread_array<const N:usize>(&mut self) ->Result<[u8;N]>
where Self:Sized,

🔬This is a nightly-only experimental API. (read_array #148848)
Read and return a fixed array of bytes from this source.Read more
1.73.0 ·Source§

implSeek forArc<File>

Source§

fnseek(&mut self, pos:SeekFrom) ->Result<u64>

Seek to an offset, in bytes, in a stream.Read more
Source§

fnstream_len(&mut self) ->Result<u64>

🔬This is a nightly-only experimental API. (seek_stream_len #59359)
Returns the length of this stream (in bytes).Read more
Source§

fnstream_position(&mut self) ->Result<u64>

Returns the current seek position from the start of the stream.Read more
1.55.0 ·Source§

fnrewind(&mut self) ->Result<()>

Rewind to the beginning of a stream.Read more
1.80.0 ·Source§

fnseek_relative(&mut self, offset:i64) ->Result<()>

Seeks relative to the current position.Read more
1.43.0 ·Source§

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

Source§

typeError =Arc<[T], A>

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

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

Performs the conversion.
1.73.0 ·Source§

implWrite forArc<File>

Source§

fnwrite(&mut self, buf: &[u8]) ->Result<usize>

Writes a buffer into this writer, returning how many bytes were written.Read more
Source§

fnwrite_vectored(&mut self, bufs: &[IoSlice<'_>]) ->Result<usize>

Likewrite, except that it writes from a slice of buffers.Read more
Source§

fnis_write_vectored(&self) ->bool

🔬This is a nightly-only experimental API. (can_vector #69941)
Determines if thisWriter has an efficientwrite_vectoredimplementation.Read more
Source§

fnflush(&mut self) ->Result<()>

Flushes this output stream, ensuring that all intermediately bufferedcontents reach their destination.Read more
1.0.0 ·Source§

fnwrite_all(&mut self, buf: &[u8]) ->Result<()>

Attempts to write an entire buffer into this writer.Read more
Source§

fnwrite_all_vectored(&mut self, bufs: &mut [IoSlice<'_>]) ->Result<()>

🔬This is a nightly-only experimental API. (write_all_vectored #70436)
Attempts to write multiple buffers into this writer.Read more
1.0.0 ·Source§

fnwrite_fmt(&mut self, args:Arguments<'_>) ->Result<()>

Writes a formatted string into this writer, returning any errorencountered.Read more
1.0.0 ·Source§

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

Creates a “by reference” adapter for this instance ofWrite.Read more
Source§

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

Source§

impl<T, U, A>CoerceUnsized<Arc<U, A>> forArc<T, A>
where T:Unsize<U> + ?Sized, A:Allocator, U: ?Sized,

Source§

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

Source§

impl<T, U>DispatchFromDyn<Arc<U>> forArc<T>
where T:Unsize<U> + ?Sized, U: ?Sized,

1.0.0 ·Source§

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

Source§

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

1.0.0 ·Source§

impl<T, A>Send forArc<T, A>
where T:Sync +Send + ?Sized, A:Allocator +Send,

1.0.0 ·Source§

impl<T, A>Sync forArc<T, A>
where T:Sync +Send + ?Sized, A:Allocator +Sync,

1.33.0 ·Source§

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

1.9.0 ·Source§

impl<T, A>UnwindSafe forArc<T, A>

Source§

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

Auto Trait Implementations§

§

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

§

impl<T, A>RefUnwindSafe forArc<T, A>

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-2025 Movatter.jp