pub struct Box<T, A = Global>(_, _)
where
A: Allocator,
T: ?Sized;
Expand description
唯一拥有 T
类型堆分配的指针类型。
有关更多信息,请参见 模块级文档。
Implementations§
source§impl<T> Box<T, Global>
impl<T> Box<T, Global>
sourcepub fn new_uninit() -> Box<MaybeUninit<T>, Global>
🔬This is a nightly-only experimental API. (new_uninit
#63291)
pub fn new_uninit() -> Box<MaybeUninit<T>, Global>
new_uninit
#63291)sourcepub fn new_zeroed() -> Box<MaybeUninit<T>, Global>
🔬This is a nightly-only experimental API. (new_uninit
#63291)
pub fn new_zeroed() -> Box<MaybeUninit<T>, Global>
new_uninit
#63291)创建一个具有未初始化内容的新 Box
,并用 0
字节填充内存。
有关正确和不正确使用此方法的示例,请参见 MaybeUninit::zeroed
。
Examples
#![feature(new_uninit)]
let zero = Box::<u32>::new_zeroed();
let zero = unsafe { zero.assume_init() };
assert_eq!(*zero, 0)
Run1.33.0 · sourcepub fn pin(x: T) -> Pin<Box<T, Global>>
pub fn pin(x: T) -> Pin<Box<T, Global>>
创建一个新的 Pin<Box<T>>
。如果 T
没有实现 Unpin
,那么 x
将被固定在内存中并且无法移动。
Box
的构建和固定也可以分两步完成: Box::pin(x)
与 Box::into_pin(Box::new(x))
相同。
如果您已经有 Box<T>
,或者如果您想以与 Box::new
不同的方式构建 (pinned) Box
,请考虑使用 into_pin
。
sourcepub fn try_new(x: T) -> Result<Box<T, Global>, AllocError>
🔬This is a nightly-only experimental API. (allocator_api
#32838)
pub fn try_new(x: T) -> Result<Box<T, Global>, AllocError>
allocator_api
#32838)sourcepub fn try_new_uninit() -> Result<Box<MaybeUninit<T>, Global>, AllocError>
🔬This is a nightly-only experimental API. (allocator_api
#32838)
pub fn try_new_uninit() -> Result<Box<MaybeUninit<T>, Global>, AllocError>
allocator_api
#32838)sourcepub fn try_new_zeroed() -> Result<Box<MaybeUninit<T>, Global>, AllocError>
🔬This is a nightly-only experimental API. (allocator_api
#32838)
pub fn try_new_zeroed() -> Result<Box<MaybeUninit<T>, Global>, AllocError>
allocator_api
#32838)创建一个具有未初始化内容的新 Box
,堆中的内存由 0
字节填充
有关正确和不正确使用此方法的示例,请参见 MaybeUninit::zeroed
。
Examples
#![feature(allocator_api, new_uninit)]
let zero = Box::<u32>::try_new_zeroed()?;
let zero = unsafe { zero.assume_init() };
assert_eq!(*zero, 0);
Runsource§impl<T, A> Box<T, A>where
A: Allocator,
impl<T, A> Box<T, A>where A: Allocator,
sourcepub fn new_in(x: T, alloc: A) -> Box<T, A>where
A: Allocator,
🔬This is a nightly-only experimental API. (allocator_api
#32838)
pub fn new_in(x: T, alloc: A) -> Box<T, A>where A: Allocator,
allocator_api
#32838)sourcepub fn try_new_in(x: T, alloc: A) -> Result<Box<T, A>, AllocError>where
A: Allocator,
🔬This is a nightly-only experimental API. (allocator_api
#32838)
pub fn try_new_in(x: T, alloc: A) -> Result<Box<T, A>, AllocError>where A: Allocator,
allocator_api
#32838)sourcepub fn new_uninit_in(alloc: A) -> Box<MaybeUninit<T>, A>where
A: Allocator,
🔬This is a nightly-only experimental API. (allocator_api
#32838)
pub fn new_uninit_in(alloc: A) -> Box<MaybeUninit<T>, A>where A: Allocator,
allocator_api
#32838)sourcepub fn try_new_uninit_in(alloc: A) -> Result<Box<MaybeUninit<T>, A>, AllocError>where
A: Allocator,
🔬This is a nightly-only experimental API. (allocator_api
#32838)
pub fn try_new_uninit_in(alloc: A) -> Result<Box<MaybeUninit<T>, A>, AllocError>where A: Allocator,
allocator_api
#32838)sourcepub fn new_zeroed_in(alloc: A) -> Box<MaybeUninit<T>, A>where
A: Allocator,
🔬This is a nightly-only experimental API. (allocator_api
#32838)
pub fn new_zeroed_in(alloc: A) -> Box<MaybeUninit<T>, A>where A: Allocator,
allocator_api
#32838)创建一个具有未初始化内容的新 Box
,使用提供的分配器中的 0
字节填充内存。
有关正确和不正确使用此方法的示例,请参见 MaybeUninit::zeroed
。
Examples
#![feature(allocator_api, new_uninit)]
use std::alloc::System;
let zero = Box::<u32, _>::new_zeroed_in(System);
let zero = unsafe { zero.assume_init() };
assert_eq!(*zero, 0)
Runsourcepub fn try_new_zeroed_in(alloc: A) -> Result<Box<MaybeUninit<T>, A>, AllocError>where
A: Allocator,
🔬This is a nightly-only experimental API. (allocator_api
#32838)
pub fn try_new_zeroed_in(alloc: A) -> Result<Box<MaybeUninit<T>, A>, AllocError>where A: Allocator,
allocator_api
#32838)创建一个具有未初始化内容的新 Box
,使用提供的分配器中的 0
字节填充内存,如果分配失败,则返回错误,
有关正确和不正确使用此方法的示例,请参见 MaybeUninit::zeroed
。
Examples
#![feature(allocator_api, new_uninit)]
use std::alloc::System;
let zero = Box::<u32, _>::try_new_zeroed_in(System)?;
let zero = unsafe { zero.assume_init() };
assert_eq!(*zero, 0);
Runsourcepub fn pin_in(x: T, alloc: A) -> Pin<Box<T, A>>where
A: 'static + Allocator,
🔬This is a nightly-only experimental API. (allocator_api
#32838)
pub fn pin_in(x: T, alloc: A) -> Pin<Box<T, A>>where A: 'static + Allocator,
allocator_api
#32838)创建一个新的 Pin<Box<T, A>>
。如果 T
没有实现 Unpin
,那么 x
将被固定在内存中并且无法移动。
Box
的构建和固定也可以分两步完成: Box::pin_in(x, alloc)
与 Box::into_pin(Box::new_in(x, alloc))
相同。
如果您已经有 Box<T, A>
,或者如果您想以与 Box::new_in
不同的方式构建 (pinned) Box
,请考虑使用 into_pin
。
source§impl<T> Box<[T], Global>
impl<T> Box<[T], Global>
sourcepub fn new_uninit_slice(len: usize) -> Box<[MaybeUninit<T>], Global>
🔬This is a nightly-only experimental API. (new_uninit
#63291)
pub fn new_uninit_slice(len: usize) -> Box<[MaybeUninit<T>], Global>
new_uninit
#63291)sourcepub fn new_zeroed_slice(len: usize) -> Box<[MaybeUninit<T>], Global>
🔬This is a nightly-only experimental API. (new_uninit
#63291)
pub fn new_zeroed_slice(len: usize) -> Box<[MaybeUninit<T>], Global>
new_uninit
#63291)创建一个具有未初始化内容的新 boxed 切片,并用 0
字节填充内存。
有关正确和不正确使用此方法的示例,请参见 MaybeUninit::zeroed
。
Examples
#![feature(new_uninit)]
let values = Box::<[u32]>::new_zeroed_slice(3);
let values = unsafe { values.assume_init() };
assert_eq!(*values, [0, 0, 0])
Runsourcepub fn try_new_uninit_slice(
len: usize
) -> Result<Box<[MaybeUninit<T>], Global>, AllocError>
🔬This is a nightly-only experimental API. (allocator_api
#32838)
pub fn try_new_uninit_slice( len: usize ) -> Result<Box<[MaybeUninit<T>], Global>, AllocError>
allocator_api
#32838)创建一个具有未初始化内容的新 boxed 切片。 如果分配失败,则返回一个错误
Examples
#![feature(allocator_api, new_uninit)]
let mut values = Box::<[u32]>::try_new_uninit_slice(3)?;
let values = unsafe {
// 延迟初始化:
values[0].as_mut_ptr().write(1);
values[1].as_mut_ptr().write(2);
values[2].as_mut_ptr().write(3);
values.assume_init()
};
assert_eq!(*values, [1, 2, 3]);
Runsourcepub fn try_new_zeroed_slice(
len: usize
) -> Result<Box<[MaybeUninit<T>], Global>, AllocError>
🔬This is a nightly-only experimental API. (allocator_api
#32838)
pub fn try_new_zeroed_slice( len: usize ) -> Result<Box<[MaybeUninit<T>], Global>, AllocError>
allocator_api
#32838)创建一个具有未初始化内容的新 boxed 切片,并用 0
字节填充内存。
如果分配失败,则返回一个错误
有关正确和不正确使用此方法的示例,请参见 MaybeUninit::zeroed
。
Examples
#![feature(allocator_api, new_uninit)]
let values = Box::<[u32]>::try_new_zeroed_slice(3)?;
let values = unsafe { values.assume_init() };
assert_eq!(*values, [0, 0, 0]);
Runsource§impl<T, A> Box<[T], A>where
A: Allocator,
impl<T, A> Box<[T], A>where A: Allocator,
sourcepub fn new_uninit_slice_in(len: usize, alloc: A) -> Box<[MaybeUninit<T>], A>
🔬This is a nightly-only experimental API. (allocator_api
#32838)
pub fn new_uninit_slice_in(len: usize, alloc: A) -> Box<[MaybeUninit<T>], A>
allocator_api
#32838)使用提供的分配器中未初始化的内容创建一个新的 boxed 切片。
Examples
#![feature(allocator_api, new_uninit)]
use std::alloc::System;
let mut values = Box::<[u32], _>::new_uninit_slice_in(3, System);
let values = unsafe {
// 延迟初始化:
values[0].as_mut_ptr().write(1);
values[1].as_mut_ptr().write(2);
values[2].as_mut_ptr().write(3);
values.assume_init()
};
assert_eq!(*values, [1, 2, 3])
Runsourcepub fn new_zeroed_slice_in(len: usize, alloc: A) -> Box<[MaybeUninit<T>], A>
🔬This is a nightly-only experimental API. (allocator_api
#32838)
pub fn new_zeroed_slice_in(len: usize, alloc: A) -> Box<[MaybeUninit<T>], A>
allocator_api
#32838)使用提供的分配器中未初始化的内容创建一个新的 boxed 切片,并用 0
字节填充内存。
有关正确和不正确使用此方法的示例,请参见 MaybeUninit::zeroed
。
Examples
#![feature(allocator_api, new_uninit)]
use std::alloc::System;
let values = Box::<[u32], _>::new_zeroed_slice_in(3, System);
let values = unsafe { values.assume_init() };
assert_eq!(*values, [0, 0, 0])
Runsource§impl<T, A> Box<MaybeUninit<T>, A>where
A: Allocator,
impl<T, A> Box<MaybeUninit<T>, A>where A: Allocator,
sourcepub unsafe fn assume_init(self) -> Box<T, A>
🔬This is a nightly-only experimental API. (new_uninit
#63291)
pub unsafe fn assume_init(self) -> Box<T, A>
new_uninit
#63291)转换为 Box<T, A>
。
Safety
与 MaybeUninit::assume_init
一样,由调用者负责确保该值确实处于初始化状态。
在内容尚未完全初始化时调用此方法会立即导致未定义的行为。
Examples
#![feature(new_uninit)]
let mut five = Box::<u32>::new_uninit();
let five: Box<u32> = unsafe {
// 延迟初始化:
five.as_mut_ptr().write(5);
five.assume_init()
};
assert_eq!(*five, 5)
Runsourcepub fn write(boxed: Box<MaybeUninit<T>, A>, value: T) -> Box<T, A>
🔬This is a nightly-only experimental API. (new_uninit
#63291)
pub fn write(boxed: Box<MaybeUninit<T>, A>, value: T) -> Box<T, A>
new_uninit
#63291)写入值并转换为 Box<T, A>
。
这种方法将 box 转换成和 Box::assume_init
类似的形式,只是在转换前将 value
写入其中,从而保证了安全性。
在某些情况下,使用此方法可能会提高性能,因为编译器可能能够优化从栈复制。
Examples
#![feature(new_uninit)]
let big_box = Box::<[usize; 1024]>::new_uninit();
let mut array = [0; 1024];
for (i, place) in array.iter_mut().enumerate() {
*place = i;
}
// 优化器可能会忽略此副本,所以以前的代码直接写入到堆中。
let big_box = Box::write(big_box, array);
for (i, x) in big_box.iter().enumerate() {
assert_eq!(*x, i);
}
Runsource§impl<T, A> Box<[MaybeUninit<T>], A>where
A: Allocator,
impl<T, A> Box<[MaybeUninit<T>], A>where A: Allocator,
sourcepub unsafe fn assume_init(self) -> Box<[T], A>
🔬This is a nightly-only experimental API. (new_uninit
#63291)
pub unsafe fn assume_init(self) -> Box<[T], A>
new_uninit
#63291)转换为 Box<[T], A>
。
Safety
与 MaybeUninit::assume_init
一样,由调用者负责确保值确实处于初始化状态。
在内容尚未完全初始化时调用此方法会立即导致未定义的行为。
Examples
#![feature(new_uninit)]
let mut values = Box::<[u32]>::new_uninit_slice(3);
let values = unsafe {
// 延迟初始化:
values[0].as_mut_ptr().write(1);
values[1].as_mut_ptr().write(2);
values[2].as_mut_ptr().write(3);
values.assume_init()
};
assert_eq!(*values, [1, 2, 3])
Runsource§impl<T> Box<T, Global>where
T: ?Sized,
impl<T> Box<T, Global>where T: ?Sized,
1.4.0 · sourcepub unsafe fn from_raw(raw: *mut T) -> Box<T, Global>
pub unsafe fn from_raw(raw: *mut T) -> Box<T, Global>
从裸指针构造一个 box。
调用此函数后,结果 Box
拥有裸指针。
具体来说,Box
析构函数将调用 T
的析构函数并释放分配的内存。
为了安全起见,必须根据 Box
所使用的 内存布局 分配内存。
Safety
此函数不安全,因为使用不当可能会导致内存问题。 例如,如果在同一裸指针上两次调用该函数,则可能会出现 double-free。
安全条件在 内存布局 部分中进行了描述。
Examples
重新创建以前使用 Box::into_raw
转换为裸指针的 Box
:
let x = Box::new(5);
let ptr = Box::into_raw(x);
let x = unsafe { Box::from_raw(ptr) };
Run使用二进制分配器从头开始手动创建 Box
:
use std::alloc::{alloc, Layout};
unsafe {
let ptr = alloc(Layout::new::<i32>()) as *mut i32;
// 通常,需要 .write 以避免尝试销毁 `ptr` 以前的内容,尽管对于这个简单的示例 `*ptr = 5` 也可以工作。
ptr.write(5);
let x = Box::from_raw(ptr);
}
Runsource§impl<T, A> Box<T, A>where
A: Allocator,
T: ?Sized,
impl<T, A> Box<T, A>where A: Allocator, T: ?Sized,
const: unstable · sourcepub unsafe fn from_raw_in(raw: *mut T, alloc: A) -> Box<T, A>
🔬This is a nightly-only experimental API. (allocator_api
#32838)
pub unsafe fn from_raw_in(raw: *mut T, alloc: A) -> Box<T, A>
allocator_api
#32838)从给定分配器中的裸指针构造 box。
调用此函数后,结果 Box
拥有裸指针。
具体来说,Box
析构函数将调用 T
的析构函数并释放分配的内存。
为了安全起见,必须根据 Box
所使用的 内存布局 分配内存。
Safety
此函数不安全,因为使用不当可能会导致内存问题。 例如,如果在同一裸指针上两次调用该函数,则可能会出现 double-free。
Examples
重新创建以前使用 Box::into_raw_with_allocator
转换为裸指针的 Box
:
#![feature(allocator_api)]
use std::alloc::System;
let x = Box::new_in(5, System);
let (ptr, alloc) = Box::into_raw_with_allocator(x);
let x = unsafe { Box::from_raw_in(ptr, alloc) };
Run使用系统分配器从头开始手动创建 Box
:
#![feature(allocator_api, slice_ptr_get)]
use std::alloc::{Allocator, Layout, System};
unsafe {
let ptr = System.allocate(Layout::new::<i32>())?.as_mut_ptr() as *mut i32;
// 通常,需要 .write 以避免尝试销毁 `ptr` 以前的内容,尽管对于这个简单的示例 `*ptr = 5` 也可以工作。
ptr.write(5);
let x = Box::from_raw_in(ptr, System);
}
Run1.4.0 · sourcepub fn into_raw(b: Box<T, A>) -> *mut T
pub fn into_raw(b: Box<T, A>) -> *mut T
消耗 Box
,并返回一个包装的裸指针。
指针将正确对齐且不为空。
调用此函数后,调用者将负责先前由 Box
管理的内存。
特别地,考虑到 Box
使用的 内存布局,调用者应正确销毁 T
并释放内存。
最简单的方法是使用 Box::from_raw
函数将裸指针转换回 Box
,从而允许 Box
析构函数执行清理。
Note: 这是一个关联函数,这意味着您必须将其称为 Box::into_raw(b)
而不是 b.into_raw()
。
这样就不会与内部类型的方法发生冲突。
Examples
使用 Box::from_raw
将裸指针转换回 Box
以进行自动清理:
let x = Box::new(String::from("Hello"));
let ptr = Box::into_raw(x);
let x = unsafe { Box::from_raw(ptr) };
Run通过显式运行析构函数并释放内存来进行手动清理:
use std::alloc::{dealloc, Layout};
use std::ptr;
let x = Box::new(String::from("Hello"));
let p = Box::into_raw(x);
unsafe {
ptr::drop_in_place(p);
dealloc(p as *mut u8, Layout::new::<String>());
}
Runsourcepub fn into_raw_with_allocator(b: Box<T, A>) -> (*mut T, A)
🔬This is a nightly-only experimental API. (allocator_api
#32838)
pub fn into_raw_with_allocator(b: Box<T, A>) -> (*mut T, A)
allocator_api
#32838)消耗 Box
,返回包装的裸指针和分配器。
指针将正确对齐且不为空。
调用此函数后,调用者将负责先前由 Box
管理的内存。
特别地,考虑到 Box
使用的 内存布局,调用者应正确销毁 T
并释放内存。
最简单的方法是使用 Box::from_raw_in
函数将裸指针转换回 Box
,从而允许 Box
析构函数执行清理。
Note: 这是一个关联函数,这意味着您必须将其称为 Box::into_raw_with_allocator(b)
而不是 b.into_raw_with_allocator()
。
这样就不会与内部类型的方法发生冲突。
Examples
使用 Box::from_raw_in
将裸指针转换回 Box
以进行自动清理:
#![feature(allocator_api)]
use std::alloc::System;
let x = Box::new_in(String::from("Hello"), System);
let (ptr, alloc) = Box::into_raw_with_allocator(x);
let x = unsafe { Box::from_raw_in(ptr, alloc) };
Run通过显式运行析构函数并释放内存来进行手动清理:
#![feature(allocator_api)]
use std::alloc::{Allocator, Layout, System};
use std::ptr::{self, NonNull};
let x = Box::new_in(String::from("Hello"), System);
let (ptr, alloc) = Box::into_raw_with_allocator(x);
unsafe {
ptr::drop_in_place(ptr);
let non_null = NonNull::new_unchecked(ptr);
alloc.deallocate(non_null.cast(), Layout::new::<String>());
}
Runconst: unstable · sourcepub fn allocator(b: &Box<T, A>) -> &A
🔬This is a nightly-only experimental API. (allocator_api
#32838)
pub fn allocator(b: &Box<T, A>) -> &A
allocator_api
#32838)返回底层分配器的引用。
Note: 这是一个关联函数,这意味着您必须将其称为 Box::allocator(&b)
而不是 b.allocator()
。
这样就不会与内部类型的方法发生冲突。
1.26.0 · sourcepub fn leak<'a>(b: Box<T, A>) -> &'a mut Twhere
A: 'a,
pub fn leak<'a>(b: Box<T, A>) -> &'a mut Twhere A: 'a,
消耗并泄漏 Box
,返回一个可变引用,&'a mut T
。
请注意,类型 T
必须超过所选的生命周期 'a
。
如果类型仅具有静态引用,或者根本没有静态引用,则可以将其选择为 'static
。
该函数主要用于在程序的剩余生命期内保留的数据。
丢弃返回的引用将导致内存泄漏。
如果这是不可接受的,则应首先将引用与 Box::from_raw
函数包装在一起,生成 Box
。
这个 Box
可以被丢弃,这将正确销毁 T
并释放分配的内存。
Note: 这是一个关联函数,这意味着您必须将其称为 Box::leak(b)
而不是 b.leak()
。
这样就不会与内部类型的方法发生冲突。
Examples
简单用法:
let x = Box::new(41);
let static_ref: &'static mut usize = Box::leak(x);
*static_ref += 1;
assert_eq!(*static_ref, 42);
Run未定义大小的数据:
let x = vec![1, 2, 3].into_boxed_slice();
let static_ref = Box::leak(x);
static_ref[0] = 4;
assert_eq!(*static_ref, [4, 2, 3]);
Run1.63.0 (const: unstable) · sourcepub fn into_pin(boxed: Box<T, A>) -> Pin<Box<T, A>>where
A: 'static,
pub fn into_pin(boxed: Box<T, A>) -> Pin<Box<T, A>>where A: 'static,
将 Box<T>
转换为 Pin<Box<T>>
。如果 T
没有实现 Unpin
,那么 *boxed
将被固定在内存中并且无法移动。
这种转换不会在堆上分配,而是就地进行。
也可以通过 From
获得。
使用 Box::into_pin(Box::new(x))
构造和固定 Box
也可以使用 Box::pin(x)
更简洁地编写。
如果您已经拥有 Box<T>
,或者您正在以与 Box::new
不同的方式构建 (pinned) Box
,则此 into_pin
方法很有用。
Notes
不建议 crates 添加 From<Box<T>> for Pin<T>
之类的 impl,因为它会在调用 Pin::from
时引入歧义。
下面显示了这样一个糟糕的 impl 的演示。
source§impl<A> Box<dyn Any + 'static, A>where
A: Allocator,
impl<A> Box<dyn Any + 'static, A>where A: Allocator,
sourcepub fn downcast<T>(self) -> Result<Box<T, A>, Box<dyn Any + 'static, A>>where
T: Any,
pub fn downcast<T>(self) -> Result<Box<T, A>, Box<dyn Any + 'static, A>>where T: Any,
尝试将 box 转换为具体类型。
Examples
use std::any::Any;
fn print_if_string(value: Box<dyn Any>) {
if let Ok(string) = value.downcast::<String>() {
println!("String ({}): {}", string.len(), string);
}
}
let my_string = "Hello World".to_string();
print_if_string(Box::new(my_string));
print_if_string(Box::new(0i8));
Runsourcepub unsafe fn downcast_unchecked<T>(self) -> Box<T, A>where
T: Any,
🔬This is a nightly-only experimental API. (downcast_unchecked
#90850)
pub unsafe fn downcast_unchecked<T>(self) -> Box<T, A>where T: Any,
downcast_unchecked
#90850)source§impl<A> Box<dyn Any + Send + 'static, A>where
A: Allocator,
impl<A> Box<dyn Any + Send + 'static, A>where A: Allocator,
sourcepub fn downcast<T>(self) -> Result<Box<T, A>, Box<dyn Any + Send + 'static, A>>where
T: Any,
pub fn downcast<T>(self) -> Result<Box<T, A>, Box<dyn Any + Send + 'static, A>>where T: Any,
尝试将 box 转换为具体类型。
Examples
use std::any::Any;
fn print_if_string(value: Box<dyn Any + Send>) {
if let Ok(string) = value.downcast::<String>() {
println!("String ({}): {}", string.len(), string);
}
}
let my_string = "Hello World".to_string();
print_if_string(Box::new(my_string));
print_if_string(Box::new(0i8));
Runsourcepub unsafe fn downcast_unchecked<T>(self) -> Box<T, A>where
T: Any,
🔬This is a nightly-only experimental API. (downcast_unchecked
#90850)
pub unsafe fn downcast_unchecked<T>(self) -> Box<T, A>where T: Any,
downcast_unchecked
#90850)source§impl<A> Box<dyn Any + Send + Sync + 'static, A>where
A: Allocator,
impl<A> Box<dyn Any + Send + Sync + 'static, A>where A: Allocator,
1.51.0 · sourcepub fn downcast<T>(
self
) -> Result<Box<T, A>, Box<dyn Any + Send + Sync + 'static, A>>where
T: Any,
pub fn downcast<T>( self ) -> Result<Box<T, A>, Box<dyn Any + Send + Sync + 'static, A>>where T: Any,
尝试将 box 转换为具体类型。
Examples
use std::any::Any;
fn print_if_string(value: Box<dyn Any + Send + Sync>) {
if let Ok(string) = value.downcast::<String>() {
println!("String ({}): {}", string.len(), string);
}
}
let my_string = "Hello World".to_string();
print_if_string(Box::new(my_string));
print_if_string(Box::new(0i8));
Runsourcepub unsafe fn downcast_unchecked<T>(self) -> Box<T, A>where
T: Any,
🔬This is a nightly-only experimental API. (downcast_unchecked
#90850)
pub unsafe fn downcast_unchecked<T>(self) -> Box<T, A>where T: Any,
downcast_unchecked
#90850)Trait Implementations§
1.64.0 · source§impl<T: AsFd> AsFd for Box<T>
impl<T: AsFd> AsFd for Box<T>
source§fn as_fd(&self) -> BorrowedFd<'_>
fn as_fd(&self) -> BorrowedFd<'_>
1.71.0 · source§impl<T: AsHandle> AsHandle for Box<T>
Available on Windows only.
impl<T: AsHandle> AsHandle for Box<T>
source§fn as_handle(&self) -> BorrowedHandle<'_>
fn as_handle(&self) -> BorrowedHandle<'_>
1.71.0 · source§impl<T: AsSocket> AsSocket for Box<T>
Available on Windows only.
impl<T: AsSocket> AsSocket for Box<T>
source§fn as_socket(&self) -> BorrowedSocket<'_>
fn as_socket(&self) -> BorrowedSocket<'_>
source§impl<S> AsyncIterator for Box<S, Global>where
S: AsyncIterator + Unpin + ?Sized,
impl<S> AsyncIterator for Box<S, Global>where S: AsyncIterator + Unpin + ?Sized,
§type Item = <S as AsyncIterator>::Item
type Item = <S as AsyncIterator>::Item
async_iterator
#79024)1.1.0 · source§impl<T, A> BorrowMut<T> for Box<T, A>where
A: Allocator,
T: ?Sized,
impl<T, A> BorrowMut<T> for Box<T, A>where A: Allocator, T: ?Sized,
source§fn borrow_mut(&mut self) -> &mut T
fn borrow_mut(&mut self) -> &mut T
source§impl<B: BufRead + ?Sized> BufRead for Box<B>
impl<B: BufRead + ?Sized> BufRead for Box<B>
source§fn fill_buf(&mut self) -> Result<&[u8]>
fn fill_buf(&mut self) -> Result<&[u8]>
source§fn has_data_left(&mut self) -> Result<bool>
fn has_data_left(&mut self) -> Result<bool>
buf_read_has_data_left
#86423)Read
是否有任何数据可供读取。 Read moresource§impl<T, A> Clone for Box<T, A>where
T: Clone,
A: Allocator + Clone,
impl<T, A> Clone for Box<T, A>where T: Clone, A: Allocator + Clone,
source§impl<I, A> DoubleEndedIterator for Box<I, A>where
I: DoubleEndedIterator + ?Sized,
A: Allocator,
impl<I, A> DoubleEndedIterator for Box<I, A>where I: DoubleEndedIterator + ?Sized, A: Allocator,
source§fn advance_back_by(&mut self, n: usize) -> Result<(), NonZeroUsize>
fn advance_back_by(&mut self, n: usize) -> Result<(), NonZeroUsize>
iter_advance_by
#77404)n
元素从后向前推进迭代器。 Read more1.27.0 · source§fn try_rfold<B, F, R>(&mut self, init: B, f: F) -> Rwhere
Self: Sized,
F: FnMut(B, Self::Item) -> R,
R: Try<Output = B>,
fn try_rfold<B, F, R>(&mut self, init: B, f: F) -> Rwhere Self: Sized, F: FnMut(B, Self::Item) -> R, R: Try<Output = B>,
Iterator::try_fold()
的反向版本:它从迭代器的后面开始接收元素。 Read more1.8.0 · source§impl<T> Error for Box<T, Global>where
T: Error,
impl<T> Error for Box<T, Global>where T: Error,
source§impl<I, A> ExactSizeIterator for Box<I, A>where
I: ExactSizeIterator + ?Sized,
A: Allocator,
impl<I, A> ExactSizeIterator for Box<I, A>where I: ExactSizeIterator + ?Sized, A: Allocator,
1.45.0 · source§impl Extend<Box<str, Global>> for String
impl Extend<Box<str, Global>> for String
1.35.0 · source§impl<Args, F, A> Fn<Args> for Box<F, A>where
Args: Tuple,
F: Fn<Args> + ?Sized,
A: Allocator,
impl<Args, F, A> Fn<Args> for Box<F, A>where Args: Tuple, F: Fn<Args> + ?Sized, A: Allocator,
1.35.0 · source§impl<Args, F, A> FnMut<Args> for Box<F, A>where
Args: Tuple,
F: FnMut<Args> + ?Sized,
A: Allocator,
impl<Args, F, A> FnMut<Args> for Box<F, A>where Args: Tuple, F: FnMut<Args> + ?Sized, A: Allocator,
1.35.0 · source§impl<Args, F, A> FnOnce<Args> for Box<F, A>where
Args: Tuple,
F: FnOnce<Args> + ?Sized,
A: Allocator,
impl<Args, F, A> FnOnce<Args> for Box<F, A>where Args: Tuple, F: FnOnce<Args> + ?Sized, A: Allocator,
1.6.0 · source§impl From<&str> for Box<dyn Error + 'static, Global>
impl From<&str> for Box<dyn Error + 'static, Global>
source§impl<'a> From<&str> for Box<dyn Error + Send + Sync + 'a, Global>
impl<'a> From<&str> for Box<dyn Error + Send + Sync + 'a, Global>
1.33.0 · source§impl<T, A> From<Box<T, A>> for Pin<Box<T, A>>where
A: Allocator + 'static,
T: ?Sized,
impl<T, A> From<Box<T, A>> for Pin<Box<T, A>>where A: Allocator + 'static, T: ?Sized,
source§fn from(boxed: Box<T, A>) -> Pin<Box<T, A>>
fn from(boxed: Box<T, A>) -> Pin<Box<T, A>>
将 Box<T>
转换为 Pin<Box<T>>
。如果 T
没有实现 Unpin
,那么 *boxed
将被固定在内存中并且无法移动。
这种转换不会在堆上分配,而是就地进行。
这也可以通过 Box::into_pin
获得。
使用 <Pin<Box<T>>>::from(Box::new(x))
构造和固定 Box
也可以使用 Box::pin(x)
更简洁地编写。
如果您已经拥有 Box<T>
,或者您正在以与 Box::new
不同的方式构建 (pinned) Box
,则此 From
实现很有用。
1.19.0 · source§impl<A> From<Box<str, A>> for Box<[u8], A>where
A: Allocator,
impl<A> From<Box<str, A>> for Box<[u8], A>where A: Allocator,
source§fn from(s: Box<str, A>) -> Box<[u8], A>
fn from(s: Box<str, A>) -> Box<[u8], A>
将 Box<str>
转换为 Box<[u8]>
这种转换不会在堆上分配,而是就地进行。
Examples
// 创建一个 Box<str>,该 Box<str> 将用于创建 Box<[u8]>
let boxed: Box<str> = Box::from("hello");
let boxed_str: Box<[u8]> = Box::from(boxed);
// 创建 &[u8] which 将用于创建 Box<[u8]>
let slice: &[u8] = &[104, 101, 108, 108, 111];
let boxed_slice = Box::from(slice);
assert_eq!(boxed_slice, boxed_str);
Run1.45.0 · source§impl From<Cow<'_, str>> for Box<str, Global>
impl From<Cow<'_, str>> for Box<str, Global>
source§fn from(cow: Cow<'_, str>) -> Box<str, Global>
fn from(cow: Cow<'_, str>) -> Box<str, Global>
将 Cow<'_, str>
转换为 Box<str>
当 cow
是 Cow::Borrowed
变体时,此转换在堆上分配并复制底层 str
。
否则,它将尝试重用拥有所有权的 String
的分配。
Examples
use std::borrow::Cow;
let unboxed = Cow::Borrowed("hello");
let boxed: Box<str> = Box::from(unboxed);
println!("{boxed}");
Runlet unboxed = Cow::Owned("hello".to_string());
let boxed: Box<str> = Box::from(unboxed);
println!("{boxed}");
Run1.22.0 · source§impl<'a> From<Cow<'a, str>> for Box<dyn Error + 'static, Global>
impl<'a> From<Cow<'a, str>> for Box<dyn Error + 'static, Global>
1.22.0 · source§impl<'a, 'b> From<Cow<'b, str>> for Box<dyn Error + Send + Sync + 'a, Global>
impl<'a, 'b> From<Cow<'b, str>> for Box<dyn Error + Send + Sync + 'a, Global>
source§fn from(err: Cow<'b, str>) -> Box<dyn Error + Send + Sync + 'a, Global>
fn from(err: Cow<'b, str>) -> Box<dyn Error + Send + Sync + 'a, Global>
将 Cow
转换为 Dyn Error
+ Send
+ Sync
的 box。
Examples
use std::error::Error;
use std::mem;
use std::borrow::Cow;
let a_cow_str_error = Cow::from("a str error");
let a_boxed_error = Box::<dyn Error + Send + Sync>::from(a_cow_str_error);
assert!(
mem::size_of::<Box<dyn Error + Send + Sync>>() == mem::size_of_val(&a_boxed_error))
Runsource§impl<'a, E> From<E> for Box<dyn Error + 'a, Global>where
E: Error + 'a,
impl<'a, E> From<E> for Box<dyn Error + 'a, Global>where E: Error + 'a,
source§fn from(err: E) -> Box<dyn Error + 'a, Global>
fn from(err: E) -> Box<dyn Error + 'a, Global>
将 Error
的类型转换为 dyn Error
的 box。
Examples
use std::error::Error;
use std::fmt;
use std::mem;
#[derive(Debug)]
struct AnError;
impl fmt::Display for AnError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "An error")
}
}
impl Error for AnError {}
let an_error = AnError;
assert!(0 == mem::size_of_val(&an_error));
let a_boxed_error = Box::<dyn Error>::from(an_error);
assert!(mem::size_of::<Box<dyn Error>>() == mem::size_of_val(&a_boxed_error))
Runsource§impl<'a, E> From<E> for Box<dyn Error + Send + Sync + 'a, Global>where
E: Error + Send + Sync + 'a,
impl<'a, E> From<E> for Box<dyn Error + Send + Sync + 'a, Global>where E: Error + Send + Sync + 'a,
source§fn from(err: E) -> Box<dyn Error + Send + Sync + 'a, Global>
fn from(err: E) -> Box<dyn Error + Send + Sync + 'a, Global>
将 Error
+ Send
+ Sync
的类型转换为 Dyn Error
+ Send
+ Sync
的 box。
Examples
use std::error::Error;
use std::fmt;
use std::mem;
#[derive(Debug)]
struct AnError;
impl fmt::Display for AnError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "An error")
}
}
impl Error for AnError {}
unsafe impl Send for AnError {}
unsafe impl Sync for AnError {}
let an_error = AnError;
assert!(0 == mem::size_of_val(&an_error));
let a_boxed_error = Box::<dyn Error + Send + Sync>::from(an_error);
assert!(
mem::size_of::<Box<dyn Error + Send + Sync>>() == mem::size_of_val(&a_boxed_error))
Run1.6.0 · source§impl From<String> for Box<dyn Error + 'static, Global>
impl From<String> for Box<dyn Error + 'static, Global>
source§impl From<String> for Box<dyn Error + Send + Sync + 'static, Global>
impl From<String> for Box<dyn Error + Send + Sync + 'static, Global>
source§fn from(err: String) -> Box<dyn Error + Send + Sync + 'static, Global>
fn from(err: String) -> Box<dyn Error + Send + Sync + 'static, Global>
将 String
转换为 Dyn Error
+ Send
+ Sync
的 box。
Examples
use std::error::Error;
use std::mem;
let a_string_error = "a string error".to_string();
let a_boxed_error = Box::<dyn Error + Send + Sync>::from(a_string_error);
assert!(
mem::size_of::<Box<dyn Error + Send + Sync>>() == mem::size_of_val(&a_boxed_error))
Run1.20.0 · source§impl<T, A> From<Vec<T, A>> for Box<[T], A>where
A: Allocator,
impl<T, A> From<Vec<T, A>> for Box<[T], A>where A: Allocator,
1.36.0 · source§impl<F, A> Future for Box<F, A>where
F: Future + Unpin + ?Sized,
A: Allocator + 'static,
impl<F, A> Future for Box<F, A>where F: Future + Unpin + ?Sized, A: Allocator + 'static,
source§impl<G, R, A> Generator<R> for Box<G, A>where
G: Generator<R> + Unpin + ?Sized,
A: Allocator + 'static,
impl<G, R, A> Generator<R> for Box<G, A>where G: Generator<R> + Unpin + ?Sized, A: Allocator + 'static,
source§impl<G, R, A> Generator<R> for Pin<Box<G, A>>where
G: Generator<R> + ?Sized,
A: Allocator + 'static,
impl<G, R, A> Generator<R> for Pin<Box<G, A>>where G: Generator<R> + ?Sized, A: Allocator + 'static,
1.22.0 · source§impl<T, A> Hasher for Box<T, A>where
T: Hasher + ?Sized,
A: Allocator,
impl<T, A> Hasher for Box<T, A>where T: Hasher + ?Sized, A: Allocator,
source§fn write_u128(&mut self, i: u128)
fn write_u128(&mut self, i: u128)
u128
写入此哈希器。source§fn write_usize(&mut self, i: usize)
fn write_usize(&mut self, i: usize)
usize
写入此哈希器。source§fn write_i128(&mut self, i: i128)
fn write_i128(&mut self, i: i128)
i128
写入此哈希器。source§fn write_isize(&mut self, i: isize)
fn write_isize(&mut self, i: isize)
isize
写入此哈希器。source§impl<I, A> Iterator for Box<I, A>where
I: Iterator + ?Sized,
A: Allocator,
impl<I, A> Iterator for Box<I, A>where I: Iterator + ?Sized, A: Allocator,
source§fn next_chunk<const N: usize>(
&mut self
) -> Result<[Self::Item; N], IntoIter<Self::Item, N>>where
Self: Sized,
fn next_chunk<const N: usize>( &mut self ) -> Result<[Self::Item; N], IntoIter<Self::Item, N>>where Self: Sized,
iter_next_chunk
#98326)N
值的数组。 Read moresource§fn advance_by(&mut self, n: usize) -> Result<(), NonZeroUsize>
fn advance_by(&mut self, n: usize) -> Result<(), NonZeroUsize>
iter_advance_by
#77404)n
元素使迭代器前进。 Read more1.28.0 · source§fn step_by(self, step: usize) -> StepBy<Self> ⓘwhere
Self: Sized,
fn step_by(self, step: usize) -> StepBy<Self> ⓘwhere Self: Sized,
source§fn chain<U>(self, other: U) -> Chain<Self, <U as IntoIterator>::IntoIter> ⓘwhere
Self: Sized,
U: IntoIterator<Item = Self::Item>,
fn chain<U>(self, other: U) -> Chain<Self, <U as IntoIterator>::IntoIter> ⓘwhere Self: Sized, U: IntoIterator<Item = Self::Item>,
source§fn zip<U>(self, other: U) -> Zip<Self, <U as IntoIterator>::IntoIter> ⓘwhere
Self: Sized,
U: IntoIterator,
fn zip<U>(self, other: U) -> Zip<Self, <U as IntoIterator>::IntoIter> ⓘwhere Self: Sized, U: IntoIterator,
source§fn intersperse_with<G>(self, separator: G) -> IntersperseWith<Self, G> ⓘwhere
Self: Sized,
G: FnMut() -> Self::Item,
fn intersperse_with<G>(self, separator: G) -> IntersperseWith<Self, G> ⓘwhere Self: Sized, G: FnMut() -> Self::Item,
iter_intersperse
#79524)separator
生成的项放在原始迭代器的相邻项之间。 Read moresource§fn map<B, F>(self, f: F) -> Map<Self, F> ⓘwhere
Self: Sized,
F: FnMut(Self::Item) -> B,
fn map<B, F>(self, f: F) -> Map<Self, F> ⓘwhere Self: Sized, F: FnMut(Self::Item) -> B,
1.21.0 · source§fn for_each<F>(self, f: F)where
Self: Sized,
F: FnMut(Self::Item),
fn for_each<F>(self, f: F)where Self: Sized, F: FnMut(Self::Item),
source§fn filter<P>(self, predicate: P) -> Filter<Self, P> ⓘwhere
Self: Sized,
P: FnMut(&Self::Item) -> bool,
fn filter<P>(self, predicate: P) -> Filter<Self, P> ⓘwhere Self: Sized, P: FnMut(&Self::Item) -> bool,
source§fn filter_map<B, F>(self, f: F) -> FilterMap<Self, F> ⓘwhere
Self: Sized,
F: FnMut(Self::Item) -> Option<B>,
fn filter_map<B, F>(self, f: F) -> FilterMap<Self, F> ⓘwhere Self: Sized, F: FnMut(Self::Item) -> Option<B>,
source§fn enumerate(self) -> Enumerate<Self> ⓘwhere
Self: Sized,
fn enumerate(self) -> Enumerate<Self> ⓘwhere Self: Sized,
source§fn skip_while<P>(self, predicate: P) -> SkipWhile<Self, P> ⓘwhere
Self: Sized,
P: FnMut(&Self::Item) -> bool,
fn skip_while<P>(self, predicate: P) -> SkipWhile<Self, P> ⓘwhere Self: Sized, P: FnMut(&Self::Item) -> bool,
source§fn take_while<P>(self, predicate: P) -> TakeWhile<Self, P> ⓘwhere
Self: Sized,
P: FnMut(&Self::Item) -> bool,
fn take_while<P>(self, predicate: P) -> TakeWhile<Self, P> ⓘwhere Self: Sized, P: FnMut(&Self::Item) -> bool,
1.57.0 · source§fn map_while<B, P>(self, predicate: P) -> MapWhile<Self, P> ⓘwhere
Self: Sized,
P: FnMut(Self::Item) -> Option<B>,
fn map_while<B, P>(self, predicate: P) -> MapWhile<Self, P> ⓘwhere Self: Sized, P: FnMut(Self::Item) -> Option<B>,
source§fn take(self, n: usize) -> Take<Self> ⓘwhere
Self: Sized,
fn take(self, n: usize) -> Take<Self> ⓘwhere Self: Sized,
n
元素,如果底层迭代器提前结束,则产生更少的元素。 Read moresource§fn scan<St, B, F>(self, initial_state: St, f: F) -> Scan<Self, St, F> ⓘwhere
Self: Sized,
F: FnMut(&mut St, Self::Item) -> Option<B>,
fn scan<St, B, F>(self, initial_state: St, f: F) -> Scan<Self, St, F> ⓘwhere Self: Sized, F: FnMut(&mut St, Self::Item) -> Option<B>,
source§fn flat_map<U, F>(self, f: F) -> FlatMap<Self, U, F> ⓘwhere
Self: Sized,
U: IntoIterator,
F: FnMut(Self::Item) -> U,
fn flat_map<U, F>(self, f: F) -> FlatMap<Self, U, F> ⓘwhere Self: Sized, U: IntoIterator, F: FnMut(Self::Item) -> U,
source§fn inspect<F>(self, f: F) -> Inspect<Self, F> ⓘwhere
Self: Sized,
F: FnMut(&Self::Item),
fn inspect<F>(self, f: F) -> Inspect<Self, F> ⓘwhere Self: Sized, F: FnMut(&Self::Item),
source§fn collect_into<E>(self, collection: &mut E) -> &mut Ewhere
E: Extend<Self::Item>,
Self: Sized,
fn collect_into<E>(self, collection: &mut E) -> &mut Ewhere E: Extend<Self::Item>, Self: Sized,
iter_collect_into
#94780)source§fn partition<B, F>(self, f: F) -> (B, B)where
Self: Sized,
B: Default + Extend<Self::Item>,
F: FnMut(&Self::Item) -> bool,
fn partition<B, F>(self, f: F) -> (B, B)where Self: Sized, B: Default + Extend<Self::Item>, F: FnMut(&Self::Item) -> bool,
source§fn is_partitioned<P>(self, predicate: P) -> boolwhere
Self: Sized,
P: FnMut(Self::Item) -> bool,
fn is_partitioned<P>(self, predicate: P) -> boolwhere Self: Sized, P: FnMut(Self::Item) -> bool,
iter_is_partitioned
#62544)1.27.0 · source§fn try_fold<B, F, R>(&mut self, init: B, f: F) -> Rwhere
Self: Sized,
F: FnMut(B, Self::Item) -> R,
R: Try<Output = B>,
fn try_fold<B, F, R>(&mut self, init: B, f: F) -> Rwhere Self: Sized, F: FnMut(B, Self::Item) -> R, R: Try<Output = B>,
1.27.0 · source§fn try_for_each<F, R>(&mut self, f: F) -> Rwhere
Self: Sized,
F: FnMut(Self::Item) -> R,
R: Try<Output = ()>,
fn try_for_each<F, R>(&mut self, f: F) -> Rwhere Self: Sized, F: FnMut(Self::Item) -> R, R: Try<Output = ()>,
source§fn fold<B, F>(self, init: B, f: F) -> Bwhere
Self: Sized,
F: FnMut(B, Self::Item) -> B,
fn fold<B, F>(self, init: B, f: F) -> Bwhere Self: Sized, F: FnMut(B, Self::Item) -> B,
fold
到一个累加器中,返回最终结果。 Read more1.51.0 · source§fn reduce<F>(self, f: F) -> Option<Self::Item>where
Self: Sized,
F: FnMut(Self::Item, Self::Item) -> Self::Item,
fn reduce<F>(self, f: F) -> Option<Self::Item>where Self: Sized, F: FnMut(Self::Item, Self::Item) -> Self::Item,
source§fn try_reduce<F, R>(
&mut self,
f: F
) -> <<R as Try>::Residual as Residual<Option<<R as Try>::Output>>>::TryTypewhere
Self: Sized,
F: FnMut(Self::Item, Self::Item) -> R,
R: Try<Output = Self::Item>,
<R as Try>::Residual: Residual<Option<Self::Item>>,
fn try_reduce<F, R>( &mut self, f: F ) -> <<R as Try>::Residual as Residual<Option<<R as Try>::Output>>>::TryTypewhere Self: Sized, F: FnMut(Self::Item, Self::Item) -> R, R: Try<Output = Self::Item>, <R as Try>::Residual: Residual<Option<Self::Item>>,
iterator_try_reduce
#87053)source§fn all<F>(&mut self, f: F) -> boolwhere
Self: Sized,
F: FnMut(Self::Item) -> bool,
fn all<F>(&mut self, f: F) -> boolwhere Self: Sized, F: FnMut(Self::Item) -> bool,
source§fn any<F>(&mut self, f: F) -> boolwhere
Self: Sized,
F: FnMut(Self::Item) -> bool,
fn any<F>(&mut self, f: F) -> boolwhere Self: Sized, F: FnMut(Self::Item) -> bool,
source§fn find<P>(&mut self, predicate: P) -> Option<Self::Item>where
Self: Sized,
P: FnMut(&Self::Item) -> bool,
fn find<P>(&mut self, predicate: P) -> Option<Self::Item>where Self: Sized, P: FnMut(&Self::Item) -> bool,
1.30.0 · source§fn find_map<B, F>(&mut self, f: F) -> Option<B>where
Self: Sized,
F: FnMut(Self::Item) -> Option<B>,
fn find_map<B, F>(&mut self, f: F) -> Option<B>where Self: Sized, F: FnMut(Self::Item) -> Option<B>,
source§fn try_find<F, R>(
&mut self,
f: F
) -> <<R as Try>::Residual as Residual<Option<Self::Item>>>::TryTypewhere
Self: Sized,
F: FnMut(&Self::Item) -> R,
R: Try<Output = bool>,
<R as Try>::Residual: Residual<Option<Self::Item>>,
fn try_find<F, R>( &mut self, f: F ) -> <<R as Try>::Residual as Residual<Option<Self::Item>>>::TryTypewhere Self: Sized, F: FnMut(&Self::Item) -> R, R: Try<Output = bool>, <R as Try>::Residual: Residual<Option<Self::Item>>,
try_find
#63178)source§fn position<P>(&mut self, predicate: P) -> Option<usize>where
Self: Sized,
P: FnMut(Self::Item) -> bool,
fn position<P>(&mut self, predicate: P) -> Option<usize>where Self: Sized, P: FnMut(Self::Item) -> bool,
1.6.0 · source§fn max_by_key<B, F>(self, f: F) -> Option<Self::Item>where
B: Ord,
Self: Sized,
F: FnMut(&Self::Item) -> B,
fn max_by_key<B, F>(self, f: F) -> Option<Self::Item>where B: Ord, Self: Sized, F: FnMut(&Self::Item) -> B,
1.15.0 · source§fn max_by<F>(self, compare: F) -> Option<Self::Item>where
Self: Sized,
F: FnMut(&Self::Item, &Self::Item) -> Ordering,
fn max_by<F>(self, compare: F) -> Option<Self::Item>where Self: Sized, F: FnMut(&Self::Item, &Self::Item) -> Ordering,
1.6.0 · source§fn min_by_key<B, F>(self, f: F) -> Option<Self::Item>where
B: Ord,
Self: Sized,
F: FnMut(&Self::Item) -> B,
fn min_by_key<B, F>(self, f: F) -> Option<Self::Item>where B: Ord, Self: Sized, F: FnMut(&Self::Item) -> B,
1.15.0 · source§fn min_by<F>(self, compare: F) -> Option<Self::Item>where
Self: Sized,
F: FnMut(&Self::Item, &Self::Item) -> Ordering,
fn min_by<F>(self, compare: F) -> Option<Self::Item>where Self: Sized, F: FnMut(&Self::Item, &Self::Item) -> Ordering,
source§fn unzip<A, B, FromA, FromB>(self) -> (FromA, FromB)where
FromA: Default + Extend<A>,
FromB: Default + Extend<B>,
Self: Sized + Iterator<Item = (A, B)>,
fn unzip<A, B, FromA, FromB>(self) -> (FromA, FromB)where FromA: Default + Extend<A>, FromB: Default + Extend<B>, Self: Sized + Iterator<Item = (A, B)>,
1.36.0 · source§fn copied<'a, T>(self) -> Copied<Self> ⓘwhere
T: 'a + Copy,
Self: Sized + Iterator<Item = &'a T>,
fn copied<'a, T>(self) -> Copied<Self> ⓘwhere T: 'a + Copy, Self: Sized + Iterator<Item = &'a T>,
source§fn cloned<'a, T>(self) -> Cloned<Self> ⓘwhere
T: 'a + Clone,
Self: Sized + Iterator<Item = &'a T>,
fn cloned<'a, T>(self) -> Cloned<Self> ⓘwhere T: 'a + Clone, Self: Sized + Iterator<Item = &'a T>,
source§fn array_chunks<const N: usize>(self) -> ArrayChunks<Self, N> ⓘwhere
Self: Sized,
fn array_chunks<const N: usize>(self) -> ArrayChunks<Self, N> ⓘwhere Self: Sized,
iter_array_chunks
#100450)N
个元素的迭代器。 Read more1.11.0 · source§fn product<P>(self) -> Pwhere
Self: Sized,
P: Product<Self::Item>,
fn product<P>(self) -> Pwhere Self: Sized, P: Product<Self::Item>,
source§fn cmp_by<I, F>(self, other: I, cmp: F) -> Orderingwhere
Self: Sized,
I: IntoIterator,
F: FnMut(Self::Item, <I as IntoIterator>::Item) -> Ordering,
fn cmp_by<I, F>(self, other: I, cmp: F) -> Orderingwhere Self: Sized, I: IntoIterator, F: FnMut(Self::Item, <I as IntoIterator>::Item) -> Ordering,
iter_order_by
#64295)1.5.0 · source§fn partial_cmp<I>(self, other: I) -> Option<Ordering>where
I: IntoIterator,
Self::Item: PartialOrd<<I as IntoIterator>::Item>,
Self: Sized,
fn partial_cmp<I>(self, other: I) -> Option<Ordering>where I: IntoIterator, Self::Item: PartialOrd<<I as IntoIterator>::Item>, Self: Sized,
Iterator
的 PartialOrd
元素与另一个 PartialOrd
的元素进行比较。
比较的工作方式类似于短路评估,返回结果而不比较其余元素。
一旦可以确定订单,评估就会停止并返回结果。 Read moresource§fn partial_cmp_by<I, F>(self, other: I, partial_cmp: F) -> Option<Ordering>where
Self: Sized,
I: IntoIterator,
F: FnMut(Self::Item, <I as IntoIterator>::Item) -> Option<Ordering>,
fn partial_cmp_by<I, F>(self, other: I, partial_cmp: F) -> Option<Ordering>where Self: Sized, I: IntoIterator, F: FnMut(Self::Item, <I as IntoIterator>::Item) -> Option<Ordering>,
iter_order_by
#64295)1.5.0 · source§fn eq<I>(self, other: I) -> boolwhere
I: IntoIterator,
Self::Item: PartialEq<<I as IntoIterator>::Item>,
Self: Sized,
fn eq<I>(self, other: I) -> boolwhere I: IntoIterator, Self::Item: PartialEq<<I as IntoIterator>::Item>, Self: Sized,
source§fn eq_by<I, F>(self, other: I, eq: F) -> boolwhere
Self: Sized,
I: IntoIterator,
F: FnMut(Self::Item, <I as IntoIterator>::Item) -> bool,
fn eq_by<I, F>(self, other: I, eq: F) -> boolwhere Self: Sized, I: IntoIterator, F: FnMut(Self::Item, <I as IntoIterator>::Item) -> bool,
iter_order_by
#64295)1.5.0 · source§fn ne<I>(self, other: I) -> boolwhere
I: IntoIterator,
Self::Item: PartialEq<<I as IntoIterator>::Item>,
Self: Sized,
fn ne<I>(self, other: I) -> boolwhere I: IntoIterator, Self::Item: PartialEq<<I as IntoIterator>::Item>, Self: Sized,
1.5.0 · source§fn lt<I>(self, other: I) -> boolwhere
I: IntoIterator,
Self::Item: PartialOrd<<I as IntoIterator>::Item>,
Self: Sized,
fn lt<I>(self, other: I) -> boolwhere I: IntoIterator, Self::Item: PartialOrd<<I as IntoIterator>::Item>, Self: Sized,
1.5.0 · source§fn le<I>(self, other: I) -> boolwhere
I: IntoIterator,
Self::Item: PartialOrd<<I as IntoIterator>::Item>,
Self: Sized,
fn le<I>(self, other: I) -> boolwhere I: IntoIterator, Self::Item: PartialOrd<<I as IntoIterator>::Item>, Self: Sized,
1.5.0 · source§fn gt<I>(self, other: I) -> boolwhere
I: IntoIterator,
Self::Item: PartialOrd<<I as IntoIterator>::Item>,
Self: Sized,
fn gt<I>(self, other: I) -> boolwhere I: IntoIterator, Self::Item: PartialOrd<<I as IntoIterator>::Item>, Self: Sized,
1.5.0 · source§fn ge<I>(self, other: I) -> boolwhere
I: IntoIterator,
Self::Item: PartialOrd<<I as IntoIterator>::Item>,
Self: Sized,
fn ge<I>(self, other: I) -> boolwhere I: IntoIterator, Self::Item: PartialOrd<<I as IntoIterator>::Item>, Self: Sized,
source§fn is_sorted_by<F>(self, compare: F) -> boolwhere
Self: Sized,
F: FnMut(&Self::Item, &Self::Item) -> Option<Ordering>,
fn is_sorted_by<F>(self, compare: F) -> boolwhere Self: Sized, F: FnMut(&Self::Item, &Self::Item) -> Option<Ordering>,
is_sorted
#53485)source§fn is_sorted_by_key<F, K>(self, f: F) -> boolwhere
Self: Sized,
F: FnMut(Self::Item) -> K,
K: PartialOrd<K>,
fn is_sorted_by_key<F, K>(self, f: F) -> boolwhere Self: Sized, F: FnMut(Self::Item) -> K, K: PartialOrd<K>,
is_sorted
#53485)source§impl<T, A> PartialOrd<Box<T, A>> for Box<T, A>where
T: PartialOrd<T> + ?Sized,
A: Allocator,
impl<T, A> PartialOrd<Box<T, A>> for Box<T, A>where T: PartialOrd<T> + ?Sized, A: Allocator,
source§impl<R: Read + ?Sized> Read for Box<R>
impl<R: Read + ?Sized> Read for Box<R>
source§fn read_buf(&mut self, cursor: BorrowedCursor<'_>) -> Result<()>
fn read_buf(&mut self, cursor: BorrowedCursor<'_>) -> Result<()>
read_buf
#78485)source§fn read_vectored(&mut self, bufs: &mut [IoSliceMut<'_>]) -> Result<usize>
fn read_vectored(&mut self, bufs: &mut [IoSliceMut<'_>]) -> Result<usize>
read
相似,不同之处在于它读入缓冲区的一部分。 Read moresource§fn is_read_vectored(&self) -> bool
fn is_read_vectored(&self) -> bool
can_vector
#69941)source§fn read_to_end(&mut self, buf: &mut Vec<u8>) -> Result<usize>
fn read_to_end(&mut self, buf: &mut Vec<u8>) -> Result<usize>
buf
。 Read moresource§fn read_to_string(&mut self, buf: &mut String) -> Result<usize>
fn read_to_string(&mut self, buf: &mut String) -> Result<usize>
buf
。 Read moresource§fn read_buf_exact(&mut self, cursor: BorrowedCursor<'_>) -> Result<()>
fn read_buf_exact(&mut self, cursor: BorrowedCursor<'_>) -> Result<()>
read_buf
#78485)cursor
所需的确切字节数。 Read moresource§fn by_ref(&mut self) -> &mut Selfwhere
Self: Sized,
fn by_ref(&mut self) -> &mut Selfwhere Self: Sized,
Read
实例创建一个 “by reference” 适配器。 Read more1.66.0 · source§impl<T, const N: usize> TryFrom<Vec<T, Global>> for Box<[T; N], Global>
impl<T, const N: usize> TryFrom<Vec<T, Global>> for Box<[T; N], Global>
source§fn try_from(
vec: Vec<T, Global>
) -> Result<Box<[T; N], Global>, <Box<[T; N], Global> as TryFrom<Vec<T, Global>>>::Error>
fn try_from( vec: Vec<T, Global> ) -> Result<Box<[T; N], Global>, <Box<[T; N], Global> as TryFrom<Vec<T, Global>>>::Error>
尝试将 Vec<T>
转换为 Box<[T; N]>
。
与 Vec::into_boxed_slice
一样,如果 vec.capacity() == N
是就地的,则需要重新分配。
Errors
如果 boxed_slice.len()
不等于 N
,则返回 Err
变体中的原始 Vec<T>
。
Examples
这可以与 vec!
一起用于在堆上创建一个数组:
let state: Box<[f32; 100]> = vec![1.0; 100].try_into().unwrap();
assert_eq!(state.len(), 100);
Runsource§impl<W: Write + ?Sized> Write for Box<W>
impl<W: Write + ?Sized> Write for Box<W>
source§fn is_write_vectored(&self) -> bool
fn is_write_vectored(&self) -> bool
can_vector
#69941)source§fn write_fmt(&mut self, fmt: Arguments<'_>) -> Result<()>
fn write_fmt(&mut self, fmt: Arguments<'_>) -> Result<()>
impl<T, U, A> CoerceUnsized<Box<U, A>> for Box<T, A>where T: Unsize<U> + ?Sized, A: Allocator, U: ?Sized,
impl<T, U> DispatchFromDyn<Box<U, Global>> for Box<T, Global>where T: Unsize<U> + ?Sized, U: ?Sized,
impl<T, A> Eq for Box<T, A>where T: Eq + ?Sized, A: Allocator,
impl<I, A> FusedIterator for Box<I, A>where I: FusedIterator + ?Sized, A: Allocator,
impl<T, A> Unpin for Box<T, A>where A: Allocator + 'static, T: ?Sized,
Auto Trait Implementations§
impl<T: ?Sized, A> RefUnwindSafe for Box<T, A>where A: RefUnwindSafe, T: RefUnwindSafe,
impl<T: ?Sized, A> Send for Box<T, A>where A: Send, T: Send,
impl<T: ?Sized, A> Sync for Box<T, A>where A: Sync, T: Sync,
impl<T: ?Sized, A> UnwindSafe for Box<T, A>where A: UnwindSafe, T: UnwindSafe,
Blanket Implementations§
source§impl<T> BorrowMut<T> for Twhere
T: ?Sized,
impl<T> BorrowMut<T> for Twhere T: ?Sized,
source§fn borrow_mut(&mut self) -> &mut T
fn borrow_mut(&mut self) -> &mut T
source§impl<F> IntoFuture for Fwhere
F: Future,
impl<F> IntoFuture for Fwhere F: Future,
§type IntoFuture = F
type IntoFuture = F
source§fn into_future(self) -> <F as IntoFuture>::IntoFuture
fn into_future(self) -> <F as IntoFuture>::IntoFuture
source§impl<I> IntoIterator for Iwhere
I: Iterator,
impl<I> IntoIterator for Iwhere I: Iterator,
source§impl<'a, F> Pattern<'a> for Fwhere
F: FnMut(char) -> bool,
impl<'a, F> Pattern<'a> for Fwhere F: FnMut(char) -> bool,
§type Searcher = CharPredicateSearcher<'a, F>
type Searcher = CharPredicateSearcher<'a, F>
pattern
#27721)source§fn into_searcher(self, haystack: &'a str) -> CharPredicateSearcher<'a, F>
fn into_searcher(self, haystack: &'a str) -> CharPredicateSearcher<'a, F>
pattern
#27721)self
和 haystack
构造关联的搜索器以进行搜索。source§fn is_contained_in(self, haystack: &'a str) -> bool
fn is_contained_in(self, haystack: &'a str) -> bool
pattern
#27721)source§fn is_prefix_of(self, haystack: &'a str) -> bool
fn is_prefix_of(self, haystack: &'a str) -> bool
pattern
#27721)source§fn strip_prefix_of(self, haystack: &'a str) -> Option<&'a str>
fn strip_prefix_of(self, haystack: &'a str) -> Option<&'a str>
pattern
#27721)source§fn is_suffix_of(self, haystack: &'a str) -> boolwhere
CharPredicateSearcher<'a, F>: ReverseSearcher<'a>,
fn is_suffix_of(self, haystack: &'a str) -> boolwhere CharPredicateSearcher<'a, F>: ReverseSearcher<'a>,
pattern
#27721)source§fn strip_suffix_of(self, haystack: &'a str) -> Option<&'a str>where
CharPredicateSearcher<'a, F>: ReverseSearcher<'a>,
fn strip_suffix_of(self, haystack: &'a str) -> Option<&'a str>where CharPredicateSearcher<'a, F>: ReverseSearcher<'a>,
pattern
#27721)