这是用户在 2024-6-10 10:38 为 https://doc.rust-lang.org/std/option/enum.Option.html 保存的双语快照页面,由 沉浸式翻译 提供双语支持。了解如何保存?

Enum std::option::Option

1.0.0 · source ·
pub enum Option<T> {
    None,
    Some(T),
}
Expand description


Option 类型。查看更多。

Variants§

§

None

 没有值。

§

Some(T)


类型的 T 一些值。

Implementations§

source§

impl<T> Option<T>

const: 1.48.0 · source

pub const fn is_some(&self) -> bool


如果该选项为值,则返回 true

§ 例子
let x: Option<u32> = Some(2);
assert_eq!(x.is_some(), true);

let x: Option<u32> = None;
assert_eq!(x.is_some(), false);
Run
1.70.0 · source

pub fn is_some_and(self, f: impl FnOnce(T) -> bool) -> bool


如果选项为 a 且其中的值与谓词匹配,则返回 true

§ 例子
let x: Option<u32> = Some(2);
assert_eq!(x.is_some_and(|x| x > 1), true);

let x: Option<u32> = Some(0);
assert_eq!(x.is_some_and(|x| x > 1), false);

let x: Option<u32> = None;
assert_eq!(x.is_some_and(|x| x > 1), false);
Run
const: 1.48.0 · source

pub const fn is_none(&self) -> bool


如果该选项为值,则返回 true

§ 例子
let x: Option<u32> = Some(2);
assert_eq!(x.is_none(), false);

let x: Option<u32> = None;
assert_eq!(x.is_none(), true);
Run
const: 1.48.0 · source

pub const fn as_ref(&self) -> Option<&T>


&Option<T> 转换为 Option<&T> .

§ 例子


Option<usize> 计算 Option<String> as 的长度,而不移动 .该方法按值获取 self 参数,使用原始值,因此此技术用于 as_ref 首先对 Option 原始值的引用。

let text: Option<String> = Some("Hello, world!".to_string());
// First, cast `Option<String>` to `Option<&String>` with `as_ref`,
// then consume *that* with `map`, leaving `text` on the stack.
let text_length: Option<usize> = text.as_ref().map(|s| s.len());
println!("still can print text: {text:?}");
Run
const: unstable · source

pub fn as_mut(&mut self) -> Option<&mut T>


&mut Option<T> 转换为 Option<&mut T> .

§ 例子
let mut x = Some(2);
match x.as_mut() {
    Some(v) => *v = 42,
    None => {},
}
assert_eq!(x, Some(42));
Run
1.33.0 (const: unstable) · source

pub fn as_pin_ref(self: Pin<&Option<T>>) -> Option<Pin<&T>>


Pin<&Option<T>> 转换为 Option<Pin<&T>> .

1.33.0 (const: unstable) · source

pub fn as_pin_mut(self: Pin<&mut Option<T>>) -> Option<Pin<&mut T>>


Pin<&mut Option<T>> 转换为 Option<Pin<&mut T>> .

1.75.0 · source

pub fn as_slice(&self) -> &[T]


返回包含值的切片(如果有)。如果是 None ,则返回空切片。这对于在 Option or 切片上使用单一类型的迭代器非常有用。


注意:如果您有 Option<&T> 并希望获得一片 T ,您可以通过 opt.map_or(&[], std::slice::from_ref) .

§ 例子
assert_eq!(
    [Some(1234).as_slice(), None.as_slice()],
    [&[1234][..], &[][..]],
);
Run


这个函数的反数是(贴现借款):

for i in [Some(1234_u16), None] {
    assert_eq!(i.as_ref(), i.as_slice().first());
}
Run
1.75.0 · source

pub fn as_mut_slice(&mut self) -> &mut [T]


返回包含值的可变切片(如果有)。如果是 None ,则返回空切片。这对于在 Option or 切片上使用单一类型的迭代器非常有用。


注意:如果该方法采用的 而不是 Option<&mut T> &mut Option<T> ,则可以通过 opt.map_or(&mut [], std::slice::from_mut) 获取可变切片。

§ 例子
assert_eq!(
    [Some(1234).as_mut_slice(), None.as_mut_slice()],
    [&mut [1234][..], &mut [][..]],
);
Run


结果是零个或一个项目的可变切片,指向我们的原始 Option 项目:

let mut x = Some(1234);
x.as_mut_slice()[0] += 1;
assert_eq!(x, Some(1235));
Run


这种方法(贴现借款)的反面是:

assert_eq!(Some(123).as_mut_slice().first_mut(), Some(&mut 123))
Run
const: unstable · source

pub fn expect(self, msg: &str) -> T


返回包含的值,使用该 self 值。

§ 恐慌


如果值为 ,则为 ,并带有 提供的 msg 自定义紧急消息。

§ 例子
let x = Some("value");
assert_eq!(x.expect("fruits are healthy"), "value");
Run
let x: Option<&str> = None;
x.expect("fruits are healthy"); // panics with `fruits are healthy`
Run


我们建议使用 expect messages 来描述您期望 Option 应该是 Some 的原因。

let item = slice.get(0)
    .expect("slice should not be empty");
Run


提示:如果您在记不住如何表达 expect 错误消息时遇到困难,请记住将重点放在“应该”这个词上,例如“env 变量应该由废话设置”或“给定的二进制文件应该可用且可由当前用户执行”。


有关期望消息样式的更多详细信息以及我们建议背后的原因,请参阅模块文档中的部分。

const: unstable · source

pub fn unwrap(self) -> T


返回包含的值,使用该 self 值。


由于此功能可能会出现恐慌,因此通常不鼓励使用它。相反,首选使用模式匹配并显式处理大小写,或者调用 、 或 。

§ 恐慌


如果 self 值等于 ,则恐慌。

§ 例子
let x = Some("air");
assert_eq!(x.unwrap(), "air");
Run
let x: Option<&str> = None;
assert_eq!(x.unwrap(), "air"); // fails
Run
source

pub fn unwrap_or(self, default: T) -> T


返回包含的值或提供的默认值。


传递给 unwrap_or 的论点被热切地评估;如果要传递函数调用的结果,建议使用 ,这是延迟计算的。

§ 例子
assert_eq!(Some("car").unwrap_or("bike"), "car");
assert_eq!(None.unwrap_or("bike"), "bike");
Run
source

pub fn unwrap_or_else<F>(self, f: F) -> T
where F: FnOnce() -> T,


返回包含的值或从闭包计算该值。

§ 例子
let k = 10;
assert_eq!(Some(4).unwrap_or_else(|| 2 * k), 4);
assert_eq!(None.unwrap_or_else(|| 2 * k), 20);
Run
source

pub fn unwrap_or_default(self) -> T
where T: Default,


返回包含的值或默认值。


使用 self 参数 then, if , 返回包含的值,否则 if 返回该类型的 。

§ 例子
let x: Option<u32> = None;
let y: Option<u32> = Some(12);

assert_eq!(x.unwrap_or_default(), 0);
assert_eq!(y.unwrap_or_default(), 12);
Run
1.58.0 (const: unstable) · source

pub unsafe fn unwrap_unchecked(self) -> T


返回包含的值,使用该 self 值,而不检查该值是否为 。

§ 安全


调用此方法是 。

§ 例子
let x = Some("air");
assert_eq!(unsafe { x.unwrap_unchecked() }, "air");
Run
let x: Option<&str> = None;
assert_eq!(unsafe { x.unwrap_unchecked() }, "air"); // Undefined behavior!
Run
source

pub fn map<U, F>(self, f: F) -> Option<U>
where F: FnOnce(T) -> U,


通过将函数应用于包含的值 (if Some ) 或返回 None (if None ) 来 Option<T> 映射 to Option<U>

§ 例子


将 an Option<String> 的长度计算为 Option<usize> ,消耗原始:

let maybe_some_string = Some(String::from("Hello, World!"));
// `Option::map` takes self *by value*, consuming `maybe_some_string`
let maybe_some_len = maybe_some_string.map(|s| s.len());
assert_eq!(maybe_some_len, Some(13));

let x: Option<&str> = None;
assert_eq!(x.map(|s| s.len()), None);
Run
1.76.0 · source

pub fn inspect<F>(self, f: F) -> Option<T>
where F: FnOnce(&T),


调用一个函数,引用包含的值 if 。


返回原始选项。

§ 例子
let list = vec![1, 2, 3];

// prints "got: 2"
let x = list
    .get(1)
    .inspect(|x| println!("got: {x}"))
    .expect("list should be long enough");

// prints nothing
list.get(5).inspect(|x| println!("got: {x}"));
Run
source

pub fn map_or<U, F>(self, default: U, f: F) -> U
where F: FnOnce(T) -> U,


返回提供的默认结果(如果没有),或将函数应用于包含的值(如果有)。


传递给 map_or 的论点被热切地评估;如果要传递函数调用的结果,建议使用 ,这是延迟计算的。

§ 例子
let x = Some("foo");
assert_eq!(x.map_or(42, |v| v.len()), 3);

let x: Option<&str> = None;
assert_eq!(x.map_or(42, |v| v.len()), 42);
Run
source

pub fn map_or_else<U, D, F>(self, default: D, f: F) -> U
where D: FnOnce() -> U, F: FnOnce(T) -> U,


计算默认函数结果(如果没有),或将其他函数应用于包含的值(如果有)。

§ 基本示例
let k = 21;

let x = Some("foo");
assert_eq!(x.map_or_else(|| 2 * k, |v| v.len()), 3);

let x: Option<&str> = None;
assert_eq!(x.map_or_else(|| 2 * k, |v| v.len()), 42);
Run
§
处理基于结果的回退


在处理可选值时,一个有点常见的情况是,如果选项不存在,则想要调用一个容易出错的回退。此示例将命令行参数(如果存在)或文件内容分析为整数。但是,与访问命令行参数不同,读取文件是容易出错的,因此必须用 Ok .

let v: u64 = std::env::args()
   .nth(1)
   .map_or_else(|| std::fs::read_to_string("/etc/someconfig.conf"), Ok)?
   .parse()?;
Run
source

pub fn ok_or<E>(self, err: E) -> Result<T, E>


Option<T> 将 转换为 ,映射到 和 。


传递给 ok_or 的论点被热切地评估;如果要传递函数调用的结果,建议使用 ,这是延迟计算的。

§ 例子
let x = Some("foo");
assert_eq!(x.ok_or(0), Ok("foo"));

let x: Option<&str> = None;
assert_eq!(x.ok_or(0), Err(0));
Run
source

pub fn ok_or_else<E, F>(self, err: F) -> Result<T, E>
where F: FnOnce() -> E,


Option<T> 将 转换为 ,映射到 和 。

§ 例子
let x = Some("foo");
assert_eq!(x.ok_or_else(|| 0), Ok("foo"));

let x: Option<&str> = None;
assert_eq!(x.ok_or_else(|| 0), Err(0));
Run
1.40.0 · source

pub fn as_deref(&self) -> Option<&<T as Deref>::Target>
where T: Deref,


Option<T> (或 &Option<T> )转换为 Option<&T::Target> .


将原始 Option 保留在原位,创建一个引用原始 Option 的新选项,另外通过 强制执行内容。

§ 例子
let x: Option<String> = Some("hey".to_owned());
assert_eq!(x.as_deref(), Some("hey"));

let x: Option<String> = None;
assert_eq!(x.as_deref(), None);
Run
1.40.0 · source

pub fn as_deref_mut(&mut self) -> Option<&mut <T as Deref>::Target>
where T: DerefMut,


Option<T> (或 &mut Option<T> )转换为 Option<&mut T::Target> .


将原始文件 Option 保留在原位,创建一个包含对内部类型类型的可变引用的新文件。

§ 例子
let mut x: Option<String> = Some("hey".to_owned());
assert_eq!(x.as_deref_mut().map(|x| {
    x.make_ascii_uppercase();
    x
}), Some("HEY".to_owned().as_mut_str()));
Run
const: unstable · source

pub fn iter(&self) -> Iter<'_, T>


返回可能包含的值的迭代器。

§ 例子
let x = Some(4);
assert_eq!(x.iter().next(), Some(&4));

let x: Option<u32> = None;
assert_eq!(x.iter().next(), None);
Run
source

pub fn iter_mut(&mut self) -> IterMut<'_, T>


返回可能包含的值的可变迭代器。

§ 例子
let mut x = Some(4);
match x.iter_mut().next() {
    Some(v) => *v = 42,
    None => {},
}
assert_eq!(x, Some(42));

let mut x: Option<u32> = None;
assert_eq!(x.iter_mut().next(), None);
Run
source

pub fn and<U>(self, optb: Option<U>) -> Option<U>


如果选项为 ,则返回 ,否则返回 optb


传递给 and 的论点被热切地评估;如果要传递函数调用的结果,建议使用 ,这是延迟计算的。

§ 例子
let x = Some(2);
let y: Option<&str> = None;
assert_eq!(x.and(y), None);

let x: Option<u32> = None;
let y = Some("foo");
assert_eq!(x.and(y), None);

let x = Some(2);
let y = Some("foo");
assert_eq!(x.and(y), Some("foo"));

let x: Option<u32> = None;
let y: Option<&str> = None;
assert_eq!(x.and(y), None);
Run
source

pub fn and_then<U, F>(self, f: F) -> Option<U>
where F: FnOnce(T) -> Option<U>,


如果选项为 ,则返回 ,否则使用包装值调用 f 并返回结果。


某些语言将此操作称为 flatmap。

§ 例子
fn sq_then_to_string(x: u32) -> Option<String> {
    x.checked_mul(x).map(|sq| sq.to_string())
}

assert_eq!(Some(2).and_then(sq_then_to_string), Some(4.to_string()));
assert_eq!(Some(1_000_000).and_then(sq_then_to_string), None); // overflowed!
assert_eq!(None.and_then(sq_then_to_string), None);
Run


通常用于链接可能返回的易出错操作。

let arr_2d = [["A0", "A1"], ["B0", "B1"]];

let item_0_1 = arr_2d.get(0).and_then(|row| row.get(1));
assert_eq!(item_0_1, Some(&"A1"));

let item_2_0 = arr_2d.get(2).and_then(|row| row.get(0));
assert_eq!(item_2_0, None);
Run
1.27.0 · source

pub fn filter<P>(self, predicate: P) -> Option<T>
where P: FnOnce(&T) -> bool,


如果选项为 ,则返回 ,否则使用包装值调用 predicate 并返回:

  • Some(t)
    if predicate 返回 true (其中 t 是包装值),以及
  • None
    如果 predicate 返回 false


此函数的工作方式类似于 。您可以想象 Option<T> 它是一个或零个元素的迭代器。 filter() 允许您决定要保留哪些元素。

§ 例子
fn is_even(n: &i32) -> bool {
    n % 2 == 0
}

assert_eq!(None.filter(is_even), None);
assert_eq!(Some(3).filter(is_even), None);
assert_eq!(Some(4).filter(is_even), Some(4));
Run
source

pub fn or(self, optb: Option<T>) -> Option<T>


如果选项包含值,则返回该选项,否则返回 optb


传递给 or 的论点被热切地评估;如果要传递函数调用的结果,建议使用 ,这是延迟计算的。

§ 例子
let x = Some(2);
let y = None;
assert_eq!(x.or(y), Some(2));

let x = None;
let y = Some(100);
assert_eq!(x.or(y), Some(100));

let x = Some(2);
let y = Some(100);
assert_eq!(x.or(y), Some(2));

let x: Option<u32> = None;
let y = None;
assert_eq!(x.or(y), None);
Run
source

pub fn or_else<F>(self, f: F) -> Option<T>
where F: FnOnce() -> Option<T>,


如果选项包含值,则返回该选项,否则调用 f 并返回结果。

§ 例子
fn nobody() -> Option<&'static str> { None }
fn vikings() -> Option<&'static str> { Some("vikings") }

assert_eq!(Some("barbarians").or_else(vikings), Some("barbarians"));
assert_eq!(None.or_else(vikings), Some("vikings"));
assert_eq!(None.or_else(nobody), None);
Run
1.37.0 · source

pub fn xor(self, optb: Option<T>) -> Option<T>


如果 正好是 之一 selfoptb 则返回 ,否则返回 。

§ 例子
let x = Some(2);
let y: Option<u32> = None;
assert_eq!(x.xor(y), Some(2));

let x: Option<u32> = None;
let y = Some(2);
assert_eq!(x.xor(y), Some(2));

let x = Some(2);
let y = Some(2);
assert_eq!(x.xor(y), None);

let x: Option<u32> = None;
let y: Option<u32> = None;
assert_eq!(x.xor(y), None);
Run
1.53.0 · source

pub fn insert(&mut self, value: T) -> &mut T


value 插入到选项中,然后返回对它的可变引用。


如果该选项已包含值,则删除旧值。


另请参阅 ,如果选项已包含 ,则不会更新值。

§ 
let mut opt = None;
let val = opt.insert(1);
assert_eq!(*val, 1);
assert_eq!(opt.unwrap(), 1);
let val = opt.insert(2);
assert_eq!(*val, 2);
*val = 3;
assert_eq!(opt.unwrap(), 3);
Run
1.20.0 · source

pub fn get_or_insert(&mut self, value: T) -> &mut T


如果是 , value 则插入到选项中,然后返回对所包含值的可变引用。


另请参阅 ,即使选项已包含 ,也会更新该值。

§ 例子
let mut x = None;

{
    let y: &mut u32 = x.get_or_insert(5);
    assert_eq!(y, &5);

    *y = 7;
}

assert_eq!(x, Some(7));
Run
source

pub fn get_or_insert_default(&mut self) -> &mut T
where T: Default,

🔬This is a nightly-only experimental API. (option_get_or_insert_default #82901)


如果默认值是 ,则将默认值插入到选项中,然后返回对所包含值的可变引用。

§ 例子
#![feature(option_get_or_insert_default)]

let mut x = None;

{
    let y: &mut u32 = x.get_or_insert_default();
    assert_eq!(y, &0);

    *y = 7;
}

assert_eq!(x, Some(7));
Run
1.20.0 · source

pub fn get_or_insert_with<F>(&mut self, f: F) -> &mut T
where F: FnOnce() -> T,


如果是 ,则将计算得出的 f 值插入到选项中,然后返回对所包含值的可变引用。

§ 例子
let mut x = None;

{
    let y: &mut u32 = x.get_or_insert_with(|| 5);
    assert_eq!(y, &5);

    *y = 7;
}

assert_eq!(x, Some(7));
Run
const: unstable · source

pub fn take(&mut self) -> Option<T>


从选项中取出值,将 a 保留在其位置。

§ 例子
let mut x = Some(2);
let y = x.take();
assert_eq!(x, None);
assert_eq!(y, Some(2));

let mut x: Option<u32> = None;
let y = x.take();
assert_eq!(x, None);
assert_eq!(y, None);
Run
source

pub fn take_if<P>(&mut self, predicate: P) -> Option<T>
where P: FnOnce(&mut T) -> bool,

🔬This is a nightly-only experimental API. (option_take_if #98934)


从选项中取出值,但前提是谓词 true 的计算结果基于对值的可变引用。


换言之,如果谓词返回 true ,则替换 selfNone 。此方法的操作类似于,但有条件。

§ 例子
#![feature(option_take_if)]

let mut x = Some(42);

let prev = x.take_if(|v| if *v == 42 {
    *v += 1;
    false
} else {
    false
});
assert_eq!(x, Some(43));
assert_eq!(prev, None);

let prev = x.take_if(|v| *v == 43);
assert_eq!(x, None);
assert_eq!(prev, Some(43));
Run
1.31.0 (const: unstable) · source

pub fn replace(&mut self, value: T) -> Option<T>


将选项中的实际值替换为参数中给出的值,如果存在,则返回旧值,将 a 保留在其位置,而不取消初始化任何一个。

§ 例子
let mut x = Some(2);
let old = x.replace(5);
assert_eq!(x, Some(5));
assert_eq!(old, Some(2));

let mut x = None;
let old = x.replace(3);
assert_eq!(x, Some(3));
assert_eq!(old, None);
Run
1.46.0 · source

pub fn zip<U>(self, other: Option<U>) -> Option<(T, U)>


self 拉链与另一个 Option .


如果 self is Some(s)other is Some(o) ,则此方法返回 Some((s, o)) 。否则, None 将返回。

§Examples
let x = Some(1);
let y = Some("hi");
let z = None::<u8>;

assert_eq!(x.zip(y), Some((1, "hi")));
assert_eq!(x.zip(z), None);
Run
source

pub fn zip_with<U, F, R>(self, other: Option<U>, f: F) -> Option<R>
where F: FnOnce(T, U) -> R,

🔬This is a nightly-only experimental API. (option_zip #70086)


拉链 self 和另一个 Option 具有功能 f


如果 self is Some(s)other is Some(o) ,则此方法返回 Some(f(s, o)) 。否则, None 将返回。

§ 例子
#![feature(option_zip)]

#[derive(Debug, PartialEq)]
struct Point {
    x: f64,
    y: f64,
}

impl Point {
    fn new(x: f64, y: f64) -> Self {
        Self { x, y }
    }
}

let x = Some(17.5);
let y = Some(42.7);

assert_eq!(x.zip_with(y, Point::new), Some(Point { x: 17.5, y: 42.7 }));
assert_eq!(x.zip_with(None, Point::new), None);
Run
source§

impl<T, U> Option<(T, U)>

1.66.0 · source

pub fn unzip(self) -> (Option<T>, Option<U>)


解压缩包含两个选项元组的选项。


如果 selfSome((a, b)) ,此方法返回 (Some(a), Some(b)) 。否则, (None, None) 将返回。

§ 例子
let x = Some((1, "hi"));
let y = None::<(u8, u32)>;

assert_eq!(x.unzip(), (Some(1), Some("hi")));
assert_eq!(y.unzip(), (None, None));
Run
source§

impl<T> Option<&T>

1.35.0 (const: unstable) · source

pub fn copied(self) -> Option<T>
where T: Copy,

Maps an Option<&T> to an Option<T> by copying the contents of the option.

§ 例子
let x = 12;
let opt_x = Some(&x);
assert_eq!(opt_x, Some(&12));
let copied = opt_x.copied();
assert_eq!(copied, Some(12));
Run
source

pub fn cloned(self) -> Option<T>
where T: Clone,


通过克隆选项的内容将 an Option<&T> 映射到 an Option<T>

§ 例子
let x = 12;
let opt_x = Some(&x);
assert_eq!(opt_x, Some(&12));
let cloned = opt_x.cloned();
assert_eq!(cloned, Some(12));
Run
source§

impl<T> Option<&mut T>

1.35.0 (const: unstable) · source

pub fn copied(self) -> Option<T>
where T: Copy,


通过复制选项的内容将 an Option<&mut T> 映射到 an Option<T>

§ 例子
let mut x = 12;
let opt_x = Some(&mut x);
assert_eq!(opt_x, Some(&mut 12));
let copied = opt_x.copied();
assert_eq!(copied, Some(12));
Run
1.26.0 · source

pub fn cloned(self) -> Option<T>
where T: Clone,


通过克隆选项的内容将 an Option<&mut T> 映射到 an Option<T>

§ 例子
let mut x = 12;
let opt_x = Some(&mut x);
assert_eq!(opt_x, Some(&mut 12));
let cloned = opt_x.cloned();
assert_eq!(cloned, Some(12));
Run
source§

impl<T, E> Option<Result<T, E>>

1.33.0 (const: unstable) · source

pub fn transpose(self) -> Result<Option<T>, E>


将 a 的 an Option 转换为 an Option 的 。

None
将映射到 Ok(None)Some(Ok(_)) 并将 Some(Err(_)) 映射到 Ok(Some(_))Err(_)

§ 例子
#[derive(Debug, Eq, PartialEq)]
struct SomeErr;

let x: Result<Option<i32>, SomeErr> = Ok(Some(5));
let y: Option<Result<i32, SomeErr>> = Some(Ok(5));
assert_eq!(x, y.transpose());
Run
source§

impl<T> Option<Option<T>>

1.40.0 (const: unstable) · source

pub fn flatten(self) -> Option<T>


Option<Option<T>> 转换为 Option<T> .

§ 例子

 基本用法:

let x: Option<Option<u32>> = Some(Some(6));
assert_eq!(Some(6), x.flatten());

let x: Option<Option<u32>> = Some(None);
assert_eq!(None, x.flatten());

let x: Option<Option<u32>> = None;
assert_eq!(None, x.flatten());
Run


展平一次只能删除一个嵌套级别:

let x: Option<Option<Option<u32>>> = Some(Some(Some(6)));
assert_eq!(Some(Some(6)), x.flatten());
assert_eq!(Some(6), x.flatten().flatten());
Run

Trait Implementations§

source§

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

source§

fn clone(&self) -> Option<T>


返回值的副本。
Read more
source§

fn clone_from(&mut self, source: &Option<T>)


source 执行复制赋值。
Read more
source§

impl<T> Debug for Option<T>
where T: Debug,

source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), Error>


使用给定的格式化程序设置值的格式。
Read more
source§

impl<T> Default for Option<T>

source§

fn default() -> Option<T>

 返回。

§ 例子
let opt: Option<u32> = Option::default();
assert!(opt.is_none());
Run
1.30.0 · source§

impl<'a, T> From<&'a Option<T>> for Option<&'a T>

source§

fn from(o: &'a Option<T>) -> Option<&'a T>


&Option<T> 转换为 Option<&T> .

§ 例子


将 an Option<String> 转换为 Option<usize> ,保留原始文件。该方法按值获取 self 参数,使用原始值,因此此技术用于 from 首先对原始值的引用。

let s: Option<String> = Some(String::from("Hello, Rustaceans!"));
let o: Option<usize> = Option::from(&s).map(|ss: &String| ss.len());

println!("Can still print s: {s:?}");

assert_eq!(o, Some(18));
Run
1.30.0 · source§

impl<'a, T> From<&'a mut Option<T>> for Option<&'a mut T>

source§

fn from(o: &'a mut Option<T>) -> Option<&'a mut T>


&mut Option<T> 转换为 Option<&mut T>

§ 例子
let mut s = Some(String::from("Hello"));
let o: Option<&mut String> = Option::from(&mut s);

match o {
    Some(t) => *t = String::from("Hello, Rustaceans!"),
    None => (),
}

assert_eq!(s, Some(String::from("Hello, Rustaceans!")));
Run
1.12.0 · source§

impl<T> From<T> for Option<T>

source§

fn from(val: T) -> Option<T>


val 入新的 .

§ 例子
let o: Option<u8> = Option::from(67);

assert_eq!(Some(67), o);
Run
source§

impl<A, V> FromIterator<Option<A>> for Option<V>
where V: FromIterator<A>,

source§

fn from_iter<I>(iter: I) -> Option<V>
where I: IntoIterator<Item = Option<A>>,


取 : 中的每个元素,如果是,则不会再取其他元素,并返回 。如果未发生,则返回包含每个值的类型的 V 容器。

§ 例子


下面是一个递增向量中每个整数的示例。当计算会导致溢出时 add ,我们使用该返回 None 的检查变体。

let items = vec![0_u16, 1, 2];

let res: Option<Vec<u16>> = items
    .iter()
    .map(|x| x.checked_add(1))
    .collect();

assert_eq!(res, Some(vec![1, 2, 3]));
Run


如您所见,这将返回预期的有效项。


下面是另一个示例,它试图从另一个整数列表中减去一个,这次检查下溢:

let items = vec![2_u16, 1, 0];

let res: Option<Vec<u16>> = items
    .iter()
    .map(|x| x.checked_sub(1))
    .collect();

assert_eq!(res, None);
Run


由于最后一个元素为零,因此它会下溢。因此,结果值为 None


这是上一个示例的变体,表明 iter 在第一个 None .

let items = vec![3_u16, 2, 1, 10];

let mut shared = 0;

let res: Option<Vec<u16>> = items
    .iter()
    .map(|x| { shared += x; x.checked_sub(2) })
    .collect();

assert_eq!(res, None);
assert_eq!(shared, 6);
Run


由于第三个元素导致了下溢,因此没有采用其他元素,因此最终值 shared 为 6 (= 3 + 2 + 1 ),而不是 16。

source§

impl<T> FromResidual<Yeet<()>> for Option<T>

source§

fn from_residual(_: Yeet<()>) -> Option<T>

🔬This is a nightly-only experimental API. (try_trait_v2 #84277)

从兼容 Residual 类型构造类型。
Read more
source§

impl<T> FromResidual for Option<T>

source§

fn from_residual(residual: Option<Infallible>) -> Option<T>

🔬This is a nightly-only experimental API. (try_trait_v2 #84277)

从兼容 Residual 类型构造类型。
Read more
source§

impl<T> Hash for Option<T>
where T: Hash,

source§

fn hash<__H>(&self, state: &mut __H)
where __H: Hasher,


将此值馈送到给定的 .
Read more
1.3.0 · source§

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


将此类型的切片馈送到给定的 .
Read more
1.4.0 · source§

impl<'a, T> IntoIterator for &'a Option<T>

§

type Item = &'a T


要迭代的元素的类型。
§

type IntoIter = Iter<'a, T>


我们把它变成哪种迭代器?
source§

fn into_iter(self) -> Iter<'a, T>


从值创建迭代器。
Read more
1.4.0 · source§

impl<'a, T> IntoIterator for &'a mut Option<T>

§

type Item = &'a mut T


要迭代的元素的类型。
§

type IntoIter = IterMut<'a, T>


我们把它变成哪种迭代器?
source§

fn into_iter(self) -> IterMut<'a, T>


从值创建迭代器。
Read more
source§

impl<T> IntoIterator for Option<T>

source§

fn into_iter(self) -> IntoIter<T>


返回可能包含的值的使用迭代器。

§ 例子
let x = Some("string");
let v: Vec<&str> = x.into_iter().collect();
assert_eq!(v, ["string"]);

let x = None;
let v: Vec<&str> = x.into_iter().collect();
assert!(v.is_empty());
Run
§

type Item = T


要迭代的元素的类型。
§

type IntoIter = IntoIter<T>


我们把它变成哪种迭代器?
source§

impl<T> Ord for Option<T>
where T: Ord,

source§

fn cmp(&self, other: &Option<T>) -> Ordering


此方法返回 between selfother
Read more
1.21.0 · source§

fn max(self, other: Self) -> Self
where Self: Sized,


比较并返回两个值的最大值。
Read more
1.21.0 · source§

fn min(self, other: Self) -> Self
where Self: Sized,


比较并返回至少两个值。
Read more
1.50.0 · source§

fn clamp(self, min: Self, max: Self) -> Self
where Self: Sized + PartialOrd,


将值限制为特定时间间隔。
Read more
source§

impl<T> PartialEq for Option<T>
where T: PartialEq,

source§

fn eq(&self, other: &Option<T>) -> bool


此方法测试 selfother 值相等,并由 == 使用。
source§

fn ne(&self, other: &Rhs) -> bool


此方法测试 != 。默认实现几乎总是足够的,并且没有充分的理由不应被覆盖。
source§

impl<T> PartialOrd for Option<T>
where T: PartialOrd,

source§

fn partial_cmp(&self, other: &Option<T>) -> Option<Ordering>


此方法返回 和 other 值之间的 self 排序(如果存在)。
Read more
source§

fn lt(&self, other: &Rhs) -> bool


此方法测试小于 (for selfother ),并由 < 操作员使用。
Read more
source§

fn le(&self, other: &Rhs) -> bool


此方法测试小于或等于 (for selfother ),并由 <= 操作员使用。
Read more
source§

fn gt(&self, other: &Rhs) -> bool


此方法测试大于 (for selfother ),并由运算符 > 使用。
Read more
source§

fn ge(&self, other: &Rhs) -> bool


此方法测试大于或等于 (for selfother ),并由 >= 操作员使用。
Read more
1.37.0 · source§

impl<T, U> Product<Option<U>> for Option<T>
where T: Product<U>,

source§

fn product<I>(iter: I) -> Option<T>
where I: Iterator<Item = Option<U>>,


取 : 中的每个元素,如果它是 ,则不会取其他元素,并返回 。如果没有发生,则返回所有元素的乘积。

§ 例子


这会将字符串向量中的每个数字相乘,如果无法解析字符串,则操作返回 None

let nums = vec!["5", "10", "1", "2"];
let total: Option<usize> = nums.iter().map(|w| w.parse::<usize>().ok()).product();
assert_eq!(total, Some(100));
let nums = vec!["5", "10", "one", "2"];
let total: Option<usize> = nums.iter().map(|w| w.parse::<usize>().ok()).product();
assert_eq!(total, None);
Run
source§

impl<T> Residual<T> for Option<Infallible>

§

type TryType = Option<T>

🔬This is a nightly-only experimental API. (try_trait_v2_residual #91285)

此元函数的“return”类型。
1.37.0 · source§

impl<T, U> Sum<Option<U>> for Option<T>
where T: Sum<U>,

source§

fn sum<I>(iter: I) -> Option<T>
where I: Iterator<Item = Option<U>>,


取 : 中的每个元素,如果它是 ,则不会取其他元素,并返回 。如果没有发生,则返回所有元素的总和。

§ 例子


这总结了字符“a”在字符串向量中的位置,如果一个单词没有字符“a”,则操作返回 None

let words = vec!["have", "a", "great", "day"];
let total: Option<usize> = words.iter().map(|w| w.find('a')).sum();
assert_eq!(total, Some(5));
let words = vec!["have", "a", "good", "day"];
let total: Option<usize> = words.iter().map(|w| w.find('a')).sum();
assert_eq!(total, None);
Run
source§

impl<T> Try for Option<T>

§

type Output = T

🔬This is a nightly-only experimental API. (try_trait_v2 #84277)

不短路 ? 时产生的值的类型。
§

type Residual = Option<Infallible>

🔬This is a nightly-only experimental API. (try_trait_v2 #84277)

短路时传递到的 ? 值的类型。
Read more
source§

fn from_output(output: <Option<T> as Try>::Output) -> Option<T>

🔬This is a nightly-only experimental API. (try_trait_v2 #84277)

从其 Output 类型构造类型。
Read more
source§

fn branch( self ) -> ControlFlow<<Option<T> as Try>::Residual, <Option<T> as Try>::Output>

🔬This is a nightly-only experimental API. (try_trait_v2 #84277)

? 用于决定运算符是应该生成一个值(因为返回了)还是将值传播回调用方(因为返回了)。
Read more
source§

impl<T> Copy for Option<T>
where T: Copy,

source§

impl<T> Eq for Option<T>
where T: Eq,

source§

impl<T> StructuralPartialEq for Option<T>

Auto Trait Implementations§

§

impl<T> Freeze for Option<T>
where T: Freeze,

§

impl<T> RefUnwindSafe for Option<T>
where T: RefUnwindSafe,

§

impl<T> Send for Option<T>
where T: Send,

§

impl<T> Sync for Option<T>
where T: Sync,

§

impl<T> Unpin for Option<T>
where T: Unpin,

§

impl<T> UnwindSafe for Option<T>
where T: UnwindSafe,

Blanket Implementations§

source§

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

source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
source§

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

source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
source§

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

source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
source§

impl<T> From<!> for T

source§

fn from(t: !) -> T

Converts to this type from the input type.
source§

impl<T> From<T> for T

source§

fn from(t: T) -> T

Returns the argument unchanged.

source§

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

source§

fn into(self) -> U

Calls U::from(self).

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

source§

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

§

type Owned = T

The resulting type after obtaining ownership.
source§

fn to_owned(&self) -> T

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

fn clone_into(&self, target: &mut T)

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

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

§

type Error = Infallible

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

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
source§

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

§

type Error = <U as TryFrom<T>>::Error

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

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.