【问题标题】:Rust OR between two optionsRust OR 在两个选项之间
【发布时间】:2020-02-20 21:13:32
【问题描述】:

我想知道是否可以在两个选项之间执行 OR 操作。类似的东西:

let a = Some(3);
let b = None;
let result = a || b;

这里我希望result 变量具有a 的值(如果它是Some)或b 的值。

我在 Internet 上没有找到任何相关文档。

【问题讨论】:

    标签: rust operators


    【解决方案1】:

    逻辑 OR (||) 的 Rust 操作数必须是 bool。所以不可能将它与Option 或任何其他类型一起使用。

    但是请看Optiondocumentation中的or方法。

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

    你的问题可以这样解决:

    let a = Some(3);
    let b = None;
    let result = a.or(b); // result: Some(3)
    

    如果您希望结果为bool,您可以使用is_someis_none

    let result = a.or(b).is_some(); // true
    let result = None.or(None).is_some(); // false
    

    OR_ELSE

    传递给或被热切评估的参数;如果你通过 函数调用的结果,推荐使用or_else,即 懒惰地评估。

    你也可以在这样的情况下使用or_else

    let a = Some(3);
    let result = a.or(produce_option());
    

    从代码中可以看出,无论您的aSome 还是None,它都会运行produce_option,这在某些(或许多)情况下可能效率不高。

    let result = a.or_else(produce_option);
    

    这里的produce_option 只会在aNone 时被调用


    对于逻辑与 (&&),您可以使用and methodOption

    let a = None;
    let b = Some(4);
    let result = a.and(b); // result: None
    

    对于惰性评估,您可以使用 AND_THEN,例如 OR_ELSE


    UNWRAP_OR

    unwrap_orunwrap_or_else 如果您想在比较时获取选项内的值,也可以使用。但这要视情况而定,我以写这个为例:

    let a = None;
    let b = None;
    let x:i32 = a.unwrap_or(b.unwrap_or_default()); //Since `i32`'s default value is 0 `x` will be equal to 0
    
    let a = None;
    let b = Some(3);
    let x:i32 = a.unwrap_or_else(||b.unwrap_or_default()); // `x` will be eqaul to 3
    //using `unwrap_or_else` might be a better idea, because of the lazy evaluation.
    

    注意:此答案侧重于 Option,但这些都适用于具有相同错误类型Result 对象。

    【讨论】:

      猜你喜欢
      • 2013-02-23
      • 1970-01-01
      • 2020-07-28
      • 1970-01-01
      • 2014-06-27
      • 2023-03-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多