Struct Box
struct Box<T: ?Sized, A: Allocator = crate::alloc::Global>(_, _)
A pointer type that uniquely owns a heap allocation of type T.
See the module-level documentation for more.
Implementations
impl<A: Allocator> crate::boxed::Box<dyn Any + Send + Sync, A>
fn downcast<T: Any>(self: Self) -> Result<Box<T, A>, Self>Attempts to downcast the box to a concrete type.
Examples
use Any; let my_string = "Hello World".to_string; print_if_string; print_if_string;unsafe fn downcast_unchecked<T: Any>(self: Self) -> Box<T, A>Downcasts the box to a concrete type.
For a safe alternative see
downcast.Examples
use Any; let x: = Boxnew; unsafeSafety
The contained value must be of type
T. Calling this method with the incorrect type is undefined behavior.
impl<A: Allocator> crate::boxed::Box<dyn Any + Send, A>
fn downcast<T: Any>(self: Self) -> Result<Box<T, A>, Self>Attempts to downcast the box to a concrete type.
Examples
use Any; let my_string = "Hello World".to_string; print_if_string; print_if_string;unsafe fn downcast_unchecked<T: Any>(self: Self) -> Box<T, A>Downcasts the box to a concrete type.
For a safe alternative see
downcast.Examples
use Any; let x: = Boxnew; unsafeSafety
The contained value must be of type
T. Calling this method with the incorrect type is undefined behavior.
impl<A: Allocator> crate::boxed::Box<dyn Any, A>
fn downcast<T: Any>(self: Self) -> Result<Box<T, A>, Self>Attempts to downcast the box to a concrete type.
Examples
use Any; let my_string = "Hello World".to_string; print_if_string; print_if_string;unsafe fn downcast_unchecked<T: Any>(self: Self) -> Box<T, A>Downcasts the box to a concrete type.
For a safe alternative see
downcast.Examples
use Any; let x: = Boxnew; unsafeSafety
The contained value must be of type
T. Calling this method with the incorrect type is undefined behavior.
impl<T> Box<T>
fn new(x: T) -> SelfAllocates memory on the heap and then places
xinto it.This doesn't actually allocate if
Tis zero-sized.Examples
let five = Boxnew;fn new_uninit() -> Box<mem::MaybeUninit<T>>Constructs a new box with uninitialized contents.
Examples
let mut five = Box::new_uninit; // Deferred initialization: five.write; let five = unsafe ; assert_eq!fn new_zeroed() -> Box<mem::MaybeUninit<T>>Constructs a new
Boxwith uninitialized contents, with the memory being filled with0bytes.See
MaybeUninit::zeroedfor examples of correct and incorrect usage of this method.Examples
let zero = Box::new_zeroed; let zero = unsafe ; assert_eq!fn pin(x: T) -> Pin<Box<T>>Constructs a new
Pin<Box<T>>. IfTdoes not implementUnpin, thenxwill be pinned in memory and unable to be moved.Constructing and pinning of the
Boxcan also be done in two steps:Box::pin(x)does the same as[Box::into_pin]([Box::new](x)). Consider usinginto_pinif you already have aBox<T>, or if you want to construct a (pinned)Boxin a different way than withBox::new.fn try_new(x: T) -> Result<Self, AllocError>Allocates memory on the heap then places
xinto it, returning an error if the allocation failsThis doesn't actually allocate if
Tis zero-sized.Examples
let five = Boxtry_new?; # Ok::fn try_new_uninit() -> Result<Box<mem::MaybeUninit<T>>, AllocError>Constructs a new box with uninitialized contents on the heap, returning an error if the allocation fails
Examples
let mut five = Box::try_new_uninit?; // Deferred initialization: five.write; let five = unsafe ; assert_eq!; # Ok::fn try_new_zeroed() -> Result<Box<mem::MaybeUninit<T>>, AllocError>Constructs a new
Boxwith uninitialized contents, with the memory being filled with0bytes on the heapSee
MaybeUninit::zeroedfor examples of correct and incorrect usage of this method.Examples
let zero = Box::try_new_zeroed?; let zero = unsafe ; assert_eq!; # Ok::fn map<U, impl FnOnce(T) -> U: FnOnce(T) -> U>(this: Self, f: impl FnOnce(T) -> U) -> Box<U>Maps the value in a box, reusing the allocation if possible.
fis called on the value in the box, and the result is returned, also boxed.Note: this is an associated function, which means that you have to call it as
Box::map(b, f)instead ofb.map(f). This is so that there is no conflict with a method on the inner type.Examples
let b = Boxnew; let new = Boxmap; assert_eq!;fn try_map<R, impl FnOnce(T) -> R: FnOnce(T) -> R>(this: Self, f: impl FnOnce(T) -> R) -> <<R as >::Residual as Residual<Box<<R as >::Output>>>::TryType where R: Try, <R as >::Residual: Residual<Box<<R as >::Output>>Attempts to map the value in a box, reusing the allocation if possible.
fis called on the value in the box, and if the operation succeeds, the result is returned, also boxed.Note: this is an associated function, which means that you have to call it as
Box::try_map(b, f)instead ofb.try_map(f). This is so that there is no conflict with a method on the inner type.Examples
let b = Boxnew; let new = Boxtry_map.unwrap; assert_eq!;
impl<T> Box<[T]>
fn new_uninit_slice(len: usize) -> Box<[mem::MaybeUninit<T>]>Constructs a new boxed slice with uninitialized contents.
Examples
let mut values = Box::new_uninit_slice; // Deferred initialization: values.write; values.write; values.write; let values = unsafe ; assert_eq!fn new_zeroed_slice(len: usize) -> Box<[mem::MaybeUninit<T>]>Constructs a new boxed slice with uninitialized contents, with the memory being filled with
0bytes.See
MaybeUninit::zeroedfor examples of correct and incorrect usage of this method.Examples
let values = Box::new_zeroed_slice; let values = unsafe ; assert_eq!fn try_new_uninit_slice(len: usize) -> Result<Box<[mem::MaybeUninit<T>]>, AllocError>Constructs a new boxed slice with uninitialized contents. Returns an error if the allocation fails.
Examples
let mut values = Box::try_new_uninit_slice?; // Deferred initialization: values.write; values.write; values.write; let values = unsafe ; assert_eq!; # Ok::fn try_new_zeroed_slice(len: usize) -> Result<Box<[mem::MaybeUninit<T>]>, AllocError>Constructs a new boxed slice with uninitialized contents, with the memory being filled with
0bytes. Returns an error if the allocation fails.See
MaybeUninit::zeroedfor examples of correct and incorrect usage of this method.Examples
let values = Box::try_new_zeroed_slice?; let values = unsafe ; assert_eq!; # Ok::fn into_array<N: usize>(self: Self) -> Option<Box<[T; N]>>Converts the boxed slice into a boxed array.
This operation does not reallocate; the underlying array of the slice is simply reinterpreted as an array type.
If
Nis not exactly equal to the length ofself, then this method returnsNone.
impl<T, A: Allocator> Box<T, A>
fn new_in(x: T, alloc: A) -> Self where A: AllocatorAllocates memory in the given allocator then places
xinto it.This doesn't actually allocate if
Tis zero-sized.Examples
use System; let five = Boxnew_in;fn try_new_in(x: T, alloc: A) -> Result<Self, AllocError> where A: AllocatorAllocates memory in the given allocator then places
xinto it, returning an error if the allocation failsThis doesn't actually allocate if
Tis zero-sized.Examples
use System; let five = Boxtry_new_in?; # Ok::fn new_uninit_in(alloc: A) -> Box<mem::MaybeUninit<T>, A> where A: AllocatorConstructs a new box with uninitialized contents in the provided allocator.
Examples
use System; let mut five = Box::new_uninit_in; // Deferred initialization: five.write; let five = unsafe ; assert_eq!fn try_new_uninit_in(alloc: A) -> Result<Box<mem::MaybeUninit<T>, A>, AllocError> where A: AllocatorConstructs a new box with uninitialized contents in the provided allocator, returning an error if the allocation fails
Examples
use System; let mut five = Box::try_new_uninit_in?; // Deferred initialization: five.write; let five = unsafe ; assert_eq!; # Ok::fn new_zeroed_in(alloc: A) -> Box<mem::MaybeUninit<T>, A> where A: AllocatorConstructs a new
Boxwith uninitialized contents, with the memory being filled with0bytes in the provided allocator.See
MaybeUninit::zeroedfor examples of correct and incorrect usage of this method.Examples
use System; let zero = Box::new_zeroed_in; let zero = unsafe ; assert_eq!fn try_new_zeroed_in(alloc: A) -> Result<Box<mem::MaybeUninit<T>, A>, AllocError> where A: AllocatorConstructs a new
Boxwith uninitialized contents, with the memory being filled with0bytes in the provided allocator, returning an error if the allocation fails,See
MaybeUninit::zeroedfor examples of correct and incorrect usage of this method.Examples
use System; let zero = Box::try_new_zeroed_in?; let zero = unsafe ; assert_eq!; # Ok::fn pin_in(x: T, alloc: A) -> Pin<Self> where A: 'static + AllocatorConstructs a new
Pin<Box<T, A>>. IfTdoes not implementUnpin, thenxwill be pinned in memory and unable to be moved.Constructing and pinning of the
Boxcan also be done in two steps:Box::pin_in(x, alloc)does the same as[Box::into_pin]([Box::new_in](x, alloc)). Consider usinginto_pinif you already have aBox<T, A>, or if you want to construct a (pinned)Boxin a different way than withBox::new_in.fn into_boxed_slice(boxed: Self) -> Box<[T], A>Converts a
Box<T>into aBox<[T]>This conversion does not allocate on the heap and happens in place.
fn into_inner(boxed: Self) -> TConsumes the
Box, returning the wrapped value.Examples
let c = Boxnew; assert_eq!;fn take(boxed: Self) -> (T, Box<mem::MaybeUninit<T>, A>)Consumes the
Boxwithout consuming its allocation, returning the wrapped value and aBoxto the uninitialized memory where the wrapped value used to live.This can be used together with
writeto reuse the allocation for multiple boxed values.Examples
let c = Boxnew; // take the value out of the box let = Boxtake; assert_eq!; // reuse the box for a second value let c = Boxwrite; assert_eq!;
impl<T, A: Allocator> Box<[T], A>
fn new_uninit_slice_in(len: usize, alloc: A) -> Box<[mem::MaybeUninit<T>], A>Constructs a new boxed slice with uninitialized contents in the provided allocator.
Examples
use System; let mut values = Box::new_uninit_slice_in; // Deferred initialization: values.write; values.write; values.write; let values = unsafe ; assert_eq!fn new_zeroed_slice_in(len: usize, alloc: A) -> Box<[mem::MaybeUninit<T>], A>Constructs a new boxed slice with uninitialized contents in the provided allocator, with the memory being filled with
0bytes.See
MaybeUninit::zeroedfor examples of correct and incorrect usage of this method.Examples
use System; let values = Box::new_zeroed_slice_in; let values = unsafe ; assert_eq!fn try_new_uninit_slice_in(len: usize, alloc: A) -> Result<Box<[mem::MaybeUninit<T>], A>, AllocError>Constructs a new boxed slice with uninitialized contents in the provided allocator. Returns an error if the allocation fails.
Examples
use System; let mut values = Box::try_new_uninit_slice_in?; // Deferred initialization: values.write; values.write; values.write; let values = unsafe ; assert_eq!; # Ok::fn try_new_zeroed_slice_in(len: usize, alloc: A) -> Result<Box<[mem::MaybeUninit<T>], A>, AllocError>Constructs a new boxed slice with uninitialized contents in the provided allocator, with the memory being filled with
0bytes. Returns an error if the allocation fails.See
MaybeUninit::zeroedfor examples of correct and incorrect usage of this method.Examples
use System; let values = Box::try_new_zeroed_slice_in?; let values = unsafe ; assert_eq!; # Ok::
impl<T, A: Allocator> Box<[mem::MaybeUninit<T>], A>
unsafe fn assume_init(self: Self) -> Box<[T], A>Converts to
Box<[T], A>.Safety
As with
MaybeUninit::assume_init, it is up to the caller to guarantee that the values really are in an initialized state. Calling this when the content is not yet fully initialized causes immediate undefined behavior.Examples
let mut values = Box::new_uninit_slice; // Deferred initialization: values.write; values.write; values.write; let values = unsafe ; assert_eq!
impl<T, A: Allocator> Box<mem::MaybeUninit<T>, A>
unsafe fn assume_init(self: Self) -> Box<T, A>Converts to
Box<T, A>.Safety
As with
MaybeUninit::assume_init, it is up to the caller to guarantee that the value really is in an initialized state. Calling this when the content is not yet fully initialized causes immediate undefined behavior.Examples
let mut five = Box::new_uninit; // Deferred initialization: five.write; let five: = unsafe ; assert_eq!fn write(boxed: Self, value: T) -> Box<T, A>Writes the value and converts to
Box<T, A>.This method converts the box similarly to
Box::assume_initbut writesvalueinto it before conversion thus guaranteeing safety. In some scenarios use of this method may improve performance because the compiler may be able to optimize copying from stack.Examples
let big_box = Box::new_uninit; let mut array = ; for in array.iter_mut.enumerate // The optimizer may be able to elide this copy, so previous code writes // to heap directly. let big_box = Boxwrite; for in big_box.iter.enumerate
impl<T: ?Sized + CloneToUninit> Box<T>
fn clone_from_ref(src: &T) -> Box<T>Allocates memory on the heap then clones
srcinto it.This doesn't actually allocate if
srcis zero-sized.Examples
let hello: = Boxclone_from_ref;fn try_clone_from_ref(src: &T) -> Result<Box<T>, AllocError>Allocates memory on the heap then clones
srcinto it, returning an error if allocation fails.This doesn't actually allocate if
srcis zero-sized.Examples
let hello: = Boxtry_clone_from_ref?; # Ok::
impl<T: ?Sized + CloneToUninit, A: Allocator> Box<T, A>
fn clone_from_ref_in(src: &T, alloc: A) -> Box<T, A>Allocates memory in the given allocator then clones
srcinto it.This doesn't actually allocate if
srcis zero-sized.Examples
use System; let hello: = Boxclone_from_ref_in;fn try_clone_from_ref_in(src: &T, alloc: A) -> Result<Box<T, A>, AllocError>Allocates memory in the given allocator then clones
srcinto it, returning an error if allocation fails.This doesn't actually allocate if
srcis zero-sized.Examples
use System; let hello: = Boxtry_clone_from_ref_in?; # Ok::
impl<T: ?Sized> Box<T>
unsafe fn from_raw(raw: *mut T) -> SelfConstructs a box from a raw pointer.
After calling this function, the raw pointer is owned by the resulting
Box. Specifically, theBoxdestructor will call the destructor ofTand free the allocated memory. For this to be safe, the memory must have been allocated in accordance with the memory layout used byBox.Safety
This function is unsafe because improper use may lead to memory problems. For example, a double-free may occur if the function is called twice on the same raw pointer.
The raw pointer must point to a block of memory allocated by the global allocator.
The safety conditions are described in the memory layout section.
Examples
Recreate a
Boxwhich was previously converted to a raw pointer using [Box::into_raw]:let x = Boxnew; let ptr = Boxinto_raw; let x = unsafe ;Manually create a
Boxfrom scratch by using the global allocator:use ; unsafeunsafe fn from_non_null(ptr: NonNull<T>) -> SelfConstructs a box from a
NonNullpointer.After calling this function, the
NonNullpointer is owned by the resultingBox. Specifically, theBoxdestructor will call the destructor ofTand free the allocated memory. For this to be safe, the memory must have been allocated in accordance with the memory layout used byBox.Safety
This function is unsafe because improper use may lead to memory problems. For example, a double-free may occur if the function is called twice on the same
NonNullpointer.The non-null pointer must point to a block of memory allocated by the global allocator.
The safety conditions are described in the memory layout section.
Examples
Recreate a
Boxwhich was previously converted to aNonNullpointer using [Box::into_non_null]:let x = Boxnew; let non_null = Boxinto_non_null; let x = unsafe ;Manually create a
Boxfrom scratch by using the global allocator:use ; use NonNull; unsafefn into_raw(b: Self) -> *mut TConsumes the
Box, returning a wrapped raw pointer.The pointer will be properly aligned and non-null.
After calling this function, the caller is responsible for the memory previously managed by the
Box. In particular, the caller should properly destroyTand release the memory, taking into account the memory layout used byBox. The easiest way to do this is to convert the raw pointer back into aBoxwith theBox::from_rawfunction, allowing theBoxdestructor to perform the cleanup.Note: this is an associated function, which means that you have to call it as
Box::into_raw(b)instead ofb.into_raw(). This is so that there is no conflict with a method on the inner type.Examples
Converting the raw pointer back into a
BoxwithBox::from_rawfor automatic cleanup:let x = Boxnew; let ptr = Boxinto_raw; let x = unsafe ;Manual cleanup by explicitly running the destructor and deallocating the memory:
use ; use ptr; let x = Boxnew; let ptr = Boxinto_raw; unsafeNote: This is equivalent to the following:
let x = Boxnew; let ptr = Boxinto_raw; unsafefn into_non_null(b: Self) -> NonNull<T>Consumes the
Box, returning a wrappedNonNullpointer.The pointer will be properly aligned.
After calling this function, the caller is responsible for the memory previously managed by the
Box. In particular, the caller should properly destroyTand release the memory, taking into account the memory layout used byBox. The easiest way to do this is to convert theNonNullpointer back into aBoxwith theBox::from_non_nullfunction, allowing theBoxdestructor to perform the cleanup.Note: this is an associated function, which means that you have to call it as
Box::into_non_null(b)instead ofb.into_non_null(). This is so that there is no conflict with a method on the inner type.Examples
Converting the
NonNullpointer back into aBoxwithBox::from_non_nullfor automatic cleanup:let x = Boxnew; let non_null = Boxinto_non_null; let x = unsafe ;Manual cleanup by explicitly running the destructor and deallocating the memory:
use ; let x = Boxnew; let non_null = Boxinto_non_null; unsafeNote: This is equivalent to the following:
let x = Boxnew; let non_null = Boxinto_non_null; unsafe
impl<T: ?Sized, A: Allocator> Box<T, A>
unsafe fn from_raw_in(raw: *mut T, alloc: A) -> SelfConstructs a box from a raw pointer in the given allocator.
After calling this function, the raw pointer is owned by the resulting
Box. Specifically, theBoxdestructor will call the destructor ofTand free the allocated memory. For this to be safe, the memory must have been allocated in accordance with the memory layout used byBox.Safety
This function is unsafe because improper use may lead to memory problems. For example, a double-free may occur if the function is called twice on the same raw pointer.
The raw pointer must point to a block of memory allocated by
alloc.Examples
Recreate a
Boxwhich was previously converted to a raw pointer using [Box::into_raw_with_allocator]:use System; let x = Boxnew_in; let = Boxinto_raw_with_allocator; let x = unsafe ;Manually create a
Boxfrom scratch by using the system allocator:use ; unsafe # Ok::unsafe fn from_non_null_in(raw: NonNull<T>, alloc: A) -> SelfConstructs a box from a
NonNullpointer in the given allocator.After calling this function, the
NonNullpointer is owned by the resultingBox. Specifically, theBoxdestructor will call the destructor ofTand free the allocated memory. For this to be safe, the memory must have been allocated in accordance with the memory layout used byBox.Safety
This function is unsafe because improper use may lead to memory problems. For example, a double-free may occur if the function is called twice on the same raw pointer.
The non-null pointer must point to a block of memory allocated by
alloc.Examples
Recreate a
Boxwhich was previously converted to aNonNullpointer using [Box::into_non_null_with_allocator]:use System; let x = Boxnew_in; let = Boxinto_non_null_with_allocator; let x = unsafe ;Manually create a
Boxfrom scratch by using the system allocator:use ; unsafe # Ok::fn into_raw_with_allocator(b: Self) -> (*mut T, A)Consumes the
Box, returning a wrapped raw pointer and the allocator.The pointer will be properly aligned and non-null.
After calling this function, the caller is responsible for the memory previously managed by the
Box. In particular, the caller should properly destroyTand release the memory, taking into account the memory layout used byBox. The easiest way to do this is to convert the raw pointer back into aBoxwith theBox::from_raw_infunction, allowing theBoxdestructor to perform the cleanup.Note: this is an associated function, which means that you have to call it as
Box::into_raw_with_allocator(b)instead ofb.into_raw_with_allocator(). This is so that there is no conflict with a method on the inner type.Examples
Converting the raw pointer back into a
BoxwithBox::from_raw_infor automatic cleanup:use System; let x = Boxnew_in; let = Boxinto_raw_with_allocator; let x = unsafe ;Manual cleanup by explicitly running the destructor and deallocating the memory:
use ; use ; let x = Boxnew_in; let = Boxinto_raw_with_allocator; unsafefn into_non_null_with_allocator(b: Self) -> (NonNull<T>, A)Consumes the
Box, returning a wrappedNonNullpointer and the allocator.The pointer will be properly aligned.
After calling this function, the caller is responsible for the memory previously managed by the
Box. In particular, the caller should properly destroyTand release the memory, taking into account the memory layout used byBox. The easiest way to do this is to convert theNonNullpointer back into aBoxwith theBox::from_non_null_infunction, allowing theBoxdestructor to perform the cleanup.Note: this is an associated function, which means that you have to call it as
Box::into_non_null_with_allocator(b)instead ofb.into_non_null_with_allocator(). This is so that there is no conflict with a method on the inner type.Examples
Converting the
NonNullpointer back into aBoxwithBox::from_non_null_infor automatic cleanup:use System; let x = Boxnew_in; let = Boxinto_non_null_with_allocator; let x = unsafe ;Manual cleanup by explicitly running the destructor and deallocating the memory:
use ; let x = Boxnew_in; let = Boxinto_non_null_with_allocator; unsafefn as_mut_ptr(b: &mut Self) -> *mut TReturns a raw mutable pointer to the
Box's contents.The caller must ensure that the
Boxoutlives the pointer this function returns, or else it will end up dangling.This method guarantees that for the purpose of the aliasing model, this method does not materialize a reference to the underlying memory, and thus the returned pointer will remain valid when mixed with other calls to
as_ptrandas_mut_ptr. Note that calling other methods that materialize references to the memory may still invalidate this pointer. See the example below for how this guarantee can be used.Examples
Due to the aliasing guarantee, the following code is legal:
unsafefn as_ptr(b: &Self) -> *const TReturns a raw pointer to the
Box's contents.The caller must ensure that the
Boxoutlives the pointer this function returns, or else it will end up dangling.The caller must also ensure that the memory the pointer (non-transitively) points to is never written to (except inside an
UnsafeCell) using this pointer or any pointer derived from it. If you need to mutate the contents of theBox, useas_mut_ptr.This method guarantees that for the purpose of the aliasing model, this method does not materialize a reference to the underlying memory, and thus the returned pointer will remain valid when mixed with other calls to
as_ptrandas_mut_ptr. Note that calling other methods that materialize mutable references to the memory, as well as writing to this memory, may still invalidate this pointer. See the example below for how this guarantee can be used.Examples
Due to the aliasing guarantee, the following code is legal:
unsafefn allocator(b: &Self) -> &AReturns a reference to the underlying allocator.
Note: this is an associated function, which means that you have to call it as
Box::allocator(&b)instead ofb.allocator(). This is so that there is no conflict with a method on the inner type.fn leak<'a>(b: Self) -> &'a mut T where A: 'aConsumes and leaks the
Box, returning a mutable reference,&'a mut T.Note that the type
Tmust outlive the chosen lifetime'a. If the type has only static references, or none at all, then this may be chosen to be'static.This function is mainly useful for data that lives for the remainder of the program's life. Dropping the returned reference will cause a memory leak. If this is not acceptable, the reference should first be wrapped with the
Box::from_rawfunction producing aBox. ThisBoxcan then be dropped which will properly destroyTand release the allocated memory.Note: this is an associated function, which means that you have to call it as
Box::leak(b)instead ofb.leak(). This is so that there is no conflict with a method on the inner type.Examples
Simple usage:
let x = Boxnew; let static_ref: &'static mut usize = Boxleak; *static_ref += 1; assert_eq!; # // FIXME(https://github.com/rust-lang/miri/issues/3670): # // use -Zmiri-disable-leak-check instead of unleaking in tests meant to leak. # drop;Unsized data:
let x = vec!.into_boxed_slice; let static_ref = Boxleak; static_ref = 4; assert_eq!; # // FIXME(https://github.com/rust-lang/miri/issues/3670): # // use -Zmiri-disable-leak-check instead of unleaking in tests meant to leak. # drop;fn into_pin(boxed: Self) -> Pin<Self> where A: 'staticConverts a
Box<T>into aPin<Box<T>>. IfTdoes not implementUnpin, then*boxedwill be pinned in memory and unable to be moved.This conversion does not allocate on the heap and happens in place.
This is also available via
From.Constructing and pinning a
BoxwithBox::into_pin([Box::new](x))can also be written more concisely using[Box::pin](x). Thisinto_pinmethod is useful if you already have aBox<T>, or you are constructing a (pinned)Boxin a different way than withBox::new.Notes
It's not recommended that crates add an impl like
From<Box<T>> for Pin<T>, as it'll introduce an ambiguity when callingPin::from. A demonstration of such a poor impl is shown below.# use std::pin::Pin; struct Foo; // A type defined in this crate. impl From<Box<()>> for Pin<Foo> { fn from(_: Box<()>) -> Pin<Foo> { Pin::new(Foo) } } let foo = Box::new(()); let bar = Pin::from(foo);
impl Clone for Box<str>
fn clone(self: &Self) -> Self
impl Clone for crate::boxed::Box<ByteStr>
fn clone(self: &Self) -> Self
impl Clone for crate::boxed::Box<core::ffi::CStr>
fn clone(self: &Self) -> Self
impl Default for Box<str>
fn default() -> Self
impl Default for crate::boxed::Box<core::ffi::CStr>
fn default() -> Box<CStr>
impl From for crate::boxed::Box<ByteStr>
fn from(s: Box<[u8]>) -> Box<ByteStr>
impl From for crate::boxed::Box<core::ffi::CStr>
fn from(s: CString) -> Box<CStr>Converts a
CStringinto a[Box]<[CStr]>without copying or allocating.
impl From for crate::boxed::Box<core::ffi::CStr>
fn from(s: &CStr) -> Box<CStr>Converts a
&CStrinto aBox<CStr>, by copying the contents into a newly allocatedBox.
impl From for crate::boxed::Box<core::ffi::CStr>
fn from(s: &mut CStr) -> Box<CStr>Converts a
&mut CStrinto aBox<CStr>, by copying the contents into a newly allocatedBox.
impl From for crate::boxed::Box<core::ffi::CStr>
fn from(cow: Cow<'_, CStr>) -> Box<CStr>Converts a
Cow<'a, CStr>into aBox<CStr>, by copying the contents if they are borrowed.
impl From for crate::boxed::Box<[u8]>
fn from(s: Box<ByteStr>) -> Box<[u8]>
impl From for crate::boxed::Box<str>
fn from(s: &str) -> Box<str>Converts a
&strinto aBox<str>This conversion allocates on the heap and performs a copy of
s.Examples
let boxed: = Boxfrom; println!;
impl From for crate::boxed::Box<str>
fn from(cow: Cow<'_, str>) -> Box<str>Converts a
Cow<'_, str>into aBox<str>When
cowis theCow::Borrowedvariant, this conversion allocates on the heap and copies the underlyingstr. Otherwise, it will try to reuse the ownedString's allocation.Examples
use Cow; let unboxed = Borrowed; let boxed: = Boxfrom; println!;# use Cow; let unboxed = Owned; let boxed: = Boxfrom; println!;
impl From for crate::boxed::Box<str>
fn from(s: &mut str) -> Box<str>Converts a
&mut strinto aBox<str>This conversion allocates on the heap and performs a copy of
s.Examples
let mut original = Stringfrom; let original: &mut str = &mut original; let boxed: = Boxfrom; println!;
impl From for crate::boxed::Box<str>
fn from(s: String) -> Box<str>Converts the given
Stringto a boxedstrslice that is owned.Examples
let s1: String = Stringfrom; let s2: = Boxfrom; let s3: String = Stringfrom; assert_eq!
impl FromIterator for crate::boxed::Box<str>
fn from_iter<T: IntoIterator<Item = char>>(iter: T) -> Self
impl FromIterator for crate::boxed::Box<str>
fn from_iter<T: IntoIterator<Item = String>>(iter: T) -> Self
impl<'a> From for crate::boxed::Box<dyn Error + 'a>
impl<'a> From for crate::boxed::Box<dyn Error + 'a>
impl<'a> From for crate::boxed::Box<dyn Error + Send + Sync + 'a>
impl<'a> From for crate::boxed::Box<dyn Error + Send + Sync + 'a>
impl<'a> FromIterator for crate::boxed::Box<str>
fn from_iter<T: IntoIterator<Item = Cow<'a, str>>>(iter: T) -> Self
impl<'a> FromIterator for crate::boxed::Box<str>
fn from_iter<T: IntoIterator<Item = &'a char>>(iter: T) -> Self
impl<'a> FromIterator for crate::boxed::Box<str>
fn from_iter<T: IntoIterator<Item = &'a str>>(iter: T) -> Self
impl<'a, 'b> From for crate::boxed::Box<dyn Error + 'a>
impl<'a, 'b> From for crate::boxed::Box<dyn Error + Send + Sync + 'a>
impl<'a, E: Error + 'a> From for crate::boxed::Box<dyn Error + 'a>
impl<'a, E: Error + Send + Sync + 'a> From for crate::boxed::Box<dyn Error + Send + Sync + 'a>
impl<A: Allocator> From for crate::boxed::Box<[u8], A>
fn from(s: Box<str, A>) -> SelfConverts a
Box<str>into aBox<[u8]>This conversion does not allocate on the heap and happens in place.
Examples
// create a Box<str> which will be used to create a Box<[u8]> let boxed: = Boxfrom; let boxed_str: = Boxfrom; // create a &[u8] which will be used to create a Box<[u8]> let slice: & = &; let boxed_slice = Boxfrom; assert_eq!;
impl<A: Allocator> FromIterator for crate::boxed::Box<str>
fn from_iter<T: IntoIterator<Item = Box<str, A>>>(iter: T) -> Self
impl<Args: Tuple, F: AsyncFn<Args> + ?Sized, A: Allocator> AsyncFn for Box<F, A>
extern Other("\"rust-call\"") fn async_call(self: &Self, args: Args) -> <Self as >::CallRefFuture<'_>
impl<Args: Tuple, F: AsyncFnMut<Args> + ?Sized, A: Allocator> AsyncFnMut for Box<F, A>
extern Other("\"rust-call\"") fn async_call_mut(self: &mut Self, args: Args) -> <Self as >::CallRefFuture<'_>
impl<Args: Tuple, F: AsyncFnOnce<Args> + ?Sized, A: Allocator> AsyncFnOnce for Box<F, A>
extern Other("\"rust-call\"") fn async_call_once(self: Self, args: Args) -> <Self as >::CallOnceFuture
impl<Args: Tuple, F: Fn<Args> + ?Sized, A: Allocator> Fn for Box<F, A>
extern Other("\"rust-call\"") fn call(self: &Self, args: Args) -> <Self as >::Output
impl<Args: Tuple, F: FnMut<Args> + ?Sized, A: Allocator> FnMut for Box<F, A>
extern Other("\"rust-call\"") fn call_mut(self: &mut Self, args: Args) -> <Self as >::Output
impl<Args: Tuple, F: FnOnce<Args> + ?Sized, A: Allocator> FnOnce for Box<F, A>
extern Other("\"rust-call\"") fn call_once(self: Self, args: Args) -> <Self as >::Output
impl<E: Error> Error for Box<E>
fn cause(self: &Self) -> Option<&dyn Error>fn source(self: &Self) -> Option<&dyn Error + 'static>fn provide<'b>(self: &'b Self, request: &mut error::Request<'b>)
impl<F> IntoFuture for Box<T, A>
fn into_future(self: Self) -> <F as IntoFuture>::IntoFuture
impl<F> Pattern for Box<T, A>
fn into_searcher<'a>(self: Self, haystack: &'a str) -> CharPredicateSearcher<'a, F>fn is_contained_in<'a>(self: Self, haystack: &'a str) -> boolfn is_prefix_of<'a>(self: Self, haystack: &'a str) -> boolfn strip_prefix_of<'a>(self: Self, haystack: &'a str) -> Option<&'a str>fn is_suffix_of<'a>(self: Self, haystack: &'a str) -> bool where CharPredicateSearcher<'a, F>: ReverseSearcher<'a>fn strip_suffix_of<'a>(self: Self, haystack: &'a str) -> Option<&'a str> where CharPredicateSearcher<'a, F>: ReverseSearcher<'a>
impl<F: ?Sized + Future + Unpin, A: Allocator> Future for Box<F, A>
fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<<Self as >::Output>
impl<G: ?Sized + Coroutine<R> + Unpin, R, A: Allocator> Coroutine for Box<G, A>
fn resume(self: Pin<&mut Self>, arg: R) -> CoroutineState<<Self as >::Yield, <Self as >::Return>
impl<I> FromIterator for crate::boxed::Box<[I]>
fn from_iter<T: IntoIterator<Item = I>>(iter: T) -> Self
impl<I> IntoAsyncIterator for Box<T, A>
fn into_async_iter(self: Self) -> <I as IntoAsyncIterator>::IntoAsyncIter
impl<I> IntoIterator for Box<T, A>
fn into_iter(self: Self) -> I
impl<I, A: Allocator> IntoIterator for crate::boxed::Box<[I], A>
fn into_iter(self: Self) -> vec::IntoIter<I, A>
impl<I, A: Allocator> Iterator for crate::boxed::Box<[I], A>
impl<I: DoubleEndedIterator + ?Sized, A: Allocator> DoubleEndedIterator for crate::boxed::Box<I, A>
fn next_back(self: &mut Self) -> Option<<I as >::Item>fn nth_back(self: &mut Self, n: usize) -> Option<<I as >::Item>
impl<I: ExactSizeIterator + ?Sized, A: Allocator> ExactSizeIterator for crate::boxed::Box<I, A>
fn len(self: &Self) -> usizefn is_empty(self: &Self) -> bool
impl<I: FusedIterator + ?Sized, A: Allocator> FusedIterator for crate::boxed::Box<I, A>
impl<I: Iterator + ?Sized, A: Allocator> Iterator for crate::boxed::Box<I, A>
fn next(self: &mut Self) -> Option<<I as >::Item>fn size_hint(self: &Self) -> (usize, Option<usize>)fn nth(self: &mut Self, n: usize) -> Option<<I as >::Item>fn last(self: Self) -> Option<<I as >::Item>
impl<P, T> Receiver for Box<T, A>
impl<S: ?Sized + AsyncIterator + Unpin> AsyncIterator for crate::boxed::Box<S>
fn poll_next(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<<Self as >::Item>>fn size_hint(self: &Self) -> (usize, Option<usize>)
impl<T> Any for Box<T, A>
fn type_id(self: &Self) -> TypeId
impl<T> Borrow for Box<T, A>
fn borrow(self: &Self) -> &T
impl<T> BorrowMut for Box<T, A>
fn borrow_mut(self: &mut Self) -> &mut T
impl<T> CloneToUninit for Box<T, A>
unsafe fn clone_to_uninit(self: &Self, dest: *mut u8)
impl<T> Default for Box<[T]>
fn default() -> SelfCreates an empty
[T]inside aBox.
impl<T> From for Box<T, A>
fn from(t: T) -> TReturns the argument unchanged.
impl<T> From for Box<T, A>
fn from(t: never) -> T
impl<T> From for crate::boxed::Box<T>
fn from(t: T) -> SelfConverts a
Tinto aBox<T>The conversion allocates on the heap and moves
tfrom the stack into it.Examples
let x = 5; let boxed = Boxnew; assert_eq!;
impl<T> ToOwned for Box<T, A>
fn to_owned(self: &Self) -> Tfn clone_into(self: &Self, target: &mut T)
impl<T> ToString for Box<T, A>
fn to_string(self: &Self) -> String
impl<T, A> Freeze for Box<T, A>
impl<T, A> RefUnwindSafe for Box<T, A>
impl<T, A> Send for Box<T, A>
impl<T, A> Sync for Box<T, A>
impl<T, A> UnwindSafe for Box<T, A>
impl<T, A: Allocator> From for crate::boxed::Box<[T], A>
fn from(v: Vec<T, A>) -> SelfConverts a vector into a boxed slice.
Before doing the conversion, this method discards excess capacity like
Vec::shrink_to_fit.Examples
assert_eq!;Any excess capacity is removed:
let mut vec = Vecwith_capacity; vec.extend; assert_eq!;
impl<T, N: usize> From for crate::boxed::Box<[T]>
fn from(array: [T; N]) -> Box<[T]>Converts a
[T; N]into aBox<[T]>This conversion moves the array to newly heap-allocated memory.
Examples
let boxed: = Boxfrom; println!;
impl<T, N: usize> TryFrom for crate::boxed::Box<[T; N]>
fn try_from(boxed_slice: Box<[T]>) -> Result<Self, <Self as >::Error>Attempts to convert a
Box<[T]>into aBox<[T; N]>.The conversion occurs in-place and does not require a new memory allocation.
Errors
Returns the old
Box<[T]>in theErrvariant ifboxed_slice.len()does not equalN.
impl<T, N: usize> TryFrom for crate::boxed::Box<[T; N]>
fn try_from(vec: Vec<T>) -> Result<Self, <Self as >::Error>Attempts to convert a
Vec<T>into aBox<[T; N]>.Like
Vec::into_boxed_slice, this is in-place ifvec.capacity() == N, but will require a reallocation otherwise.Errors
Returns the original
Vec<T>in theErrvariant ifboxed_slice.len()does not equalN.Examples
This can be used with [
vec!] to create an array on the heap:let state: = vec!.try_into.unwrap; assert_eq!;
impl<T, U> Into for Box<T, A>
fn into(self: Self) -> UCalls
U::from(self).That is, this conversion is whatever the implementation of
[From]<T> for Uchooses to do.
impl<T, U> TryFrom for Box<T, A>
fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>
impl<T, U> TryInto for Box<T, A>
fn try_into(self: Self) -> Result<U, <U as TryFrom<T>>::Error>
impl<T: ?Sized + Allocator, A: Allocator> Allocator for Box<T, A>
fn allocate(self: &Self, layout: Layout) -> Result<NonNull<[u8]>, AllocError>fn allocate_zeroed(self: &Self, layout: Layout) -> Result<NonNull<[u8]>, AllocError>unsafe fn deallocate(self: &Self, ptr: NonNull<u8>, layout: Layout)unsafe fn grow(self: &Self, ptr: NonNull<u8>, old_layout: Layout, new_layout: Layout) -> Result<NonNull<[u8]>, AllocError>unsafe fn grow_zeroed(self: &Self, ptr: NonNull<u8>, old_layout: Layout, new_layout: Layout) -> Result<NonNull<[u8]>, AllocError>unsafe fn shrink(self: &Self, ptr: NonNull<u8>, old_layout: Layout, new_layout: Layout) -> Result<NonNull<[u8]>, AllocError>
impl<T: ?Sized + Eq, A: Allocator> Eq for Box<T, A>
impl<T: ?Sized + Hash, A: Allocator> Hash for Box<T, A>
fn hash<H: Hasher>(self: &Self, state: &mut H)
impl<T: ?Sized + Hasher, A: Allocator> Hasher for Box<T, A>
fn finish(self: &Self) -> u64fn write(self: &mut Self, bytes: &[u8])fn write_u8(self: &mut Self, i: u8)fn write_u16(self: &mut Self, i: u16)fn write_u32(self: &mut Self, i: u32)fn write_u64(self: &mut Self, i: u64)fn write_u128(self: &mut Self, i: u128)fn write_usize(self: &mut Self, i: usize)fn write_i8(self: &mut Self, i: i8)fn write_i16(self: &mut Self, i: i16)fn write_i32(self: &mut Self, i: i32)fn write_i64(self: &mut Self, i: i64)fn write_i128(self: &mut Self, i: i128)fn write_isize(self: &mut Self, i: isize)fn write_length_prefix(self: &mut Self, len: usize)fn write_str(self: &mut Self, s: &str)
impl<T: ?Sized + Ord, A: Allocator> Ord for Box<T, A>
fn cmp(self: &Self, other: &Self) -> Ordering
impl<T: ?Sized + PartialEq, A: Allocator> PartialEq for Box<T, A>
fn eq(self: &Self, other: &Self) -> boolfn ne(self: &Self, other: &Self) -> bool
impl<T: ?Sized + PartialOrd, A: Allocator> PartialOrd for Box<T, A>
fn partial_cmp(self: &Self, other: &Self) -> Option<Ordering>fn lt(self: &Self, other: &Self) -> boolfn le(self: &Self, other: &Self) -> boolfn ge(self: &Self, other: &Self) -> boolfn gt(self: &Self, other: &Self) -> bool
impl<T: ?Sized + Unsize<U>, U: ?Sized> DispatchFromDyn for Box<T, crate::alloc::Global>
impl<T: ?Sized + Unsize<U>, U: ?Sized, A: Allocator> CoerceUnsized for Box<T, A>
impl<T: ?Sized, A: Allocator> AsMut for Box<T, A>
fn as_mut(self: &mut Self) -> &mut T
impl<T: ?Sized, A: Allocator> AsRef for Box<T, A>
fn as_ref(self: &Self) -> &T
impl<T: ?Sized, A: Allocator> Borrow for Box<T, A>
fn borrow(self: &Self) -> &T
impl<T: ?Sized, A: Allocator> BorrowMut for Box<T, A>
fn borrow_mut(self: &mut Self) -> &mut T
impl<T: ?Sized, A: Allocator> Deref for Box<T, A>
fn deref(self: &Self) -> &T
impl<T: ?Sized, A: Allocator> DerefMut for Box<T, A>
fn deref_mut(self: &mut Self) -> &mut T
impl<T: ?Sized, A: Allocator> DerefPure for Box<T, A>
impl<T: ?Sized, A: Allocator> Drop for Box<T, A>
fn drop(self: &mut Self)
impl<T: ?Sized, A: Allocator> PinCoerceUnsized for Box<T, A>
impl<T: ?Sized, A: Allocator> Pointer for Box<T, A>
fn fmt(self: &Self, f: &mut fmt::Formatter<'_>) -> fmt::Result
impl<T: ?Sized, A: Allocator> Unpin for Box<T, A>
impl<T: Clone> From for crate::boxed::Box<[T]>
fn from(slice: &mut [T]) -> Box<[T]>Converts a
&mut [T]into aBox<[T]>This conversion allocates on the heap and performs a copy of
sliceand its contents.Examples
// create a &mut [u8] which will be used to create a Box<[u8]> let mut array = ; let slice: &mut = &mut array; let boxed_slice: = Boxfrom; println!;
impl<T: Clone> From for crate::boxed::Box<[T]>
fn from(cow: Cow<'_, [T]>) -> Box<[T]>Converts a
Cow<'_, [T]>into aBox<[T]>When
cowis theCow::Borrowedvariant, this conversion allocates on the heap and copies the underlying slice. Otherwise, it will try to reuse the ownedVec's allocation.
impl<T: Clone> From for crate::boxed::Box<[T]>
fn from(slice: &[T]) -> Box<[T]>Converts a
&[T]into aBox<[T]>This conversion allocates on the heap and performs a copy of
sliceand its contents.Examples
// create a &[u8] which will be used to create a Box<[u8]> let slice: & = &; let boxed_slice: = Boxfrom; println!;
impl<T: Clone, A: Allocator + Clone> Clone for Box<T, A>
fn clone(self: &Self) -> SelfReturns a new box with a
clone()of this box's contents.Examples
let x = Boxnew; let y = x.clone; // The value is the same assert_eq!; // But they are unique objects assert_ne!;fn clone_from(self: &mut Self, source: &Self)Copies
source's contents intoselfwithout creating a new allocation.Examples
let x = Boxnew; let mut y = Boxnew; let yp: *const i32 = &*y; y.clone_from; // The value is the same assert_eq!; // And no allocation occurred assert_eq!;
impl<T: Clone, A: Allocator + Clone> Clone for Box<[T], A>
fn clone(self: &Self) -> Selffn clone_from(self: &mut Self, source: &Self)Copies
source's contents intoselfwithout creating a new allocation, so long as the two are of the same length.Examples
let x = Boxnew; let mut y = Boxnew; let yp: *const = &*y; y.clone_from; // The value is the same assert_eq!; // And no allocation occurred assert_eq!;
impl<T: Default> Default for Box<T>
fn default() -> SelfCreates a
Box<T>, with theDefaultvalue forT.
impl<T: fmt::Debug + ?Sized, A: Allocator> Debug for Box<T, A>
fn fmt(self: &Self, f: &mut fmt::Formatter<'_>) -> fmt::Result
impl<T: fmt::Display + ?Sized, A: Allocator> Display for Box<T, A>
fn fmt(self: &Self, f: &mut fmt::Formatter<'_>) -> fmt::Result