如果传递谓词则返回值,否则为默认值

问题描述 投票:1回答:2

如果谓词失败,如何替换值?

为了显示:

assert_eq!((3-5).but_if(|v| v < 0).then(0), 0)

我以为OptionResult会有这样的东西允许这个,但我找不到它。

rust optional predicate
2个回答
5
投票

我以为在OptionResult会有一些东西

但这些类型都不会出现在这里。减去两个数字会产生另一个数字。

看起来你只想要一个传统的if-else语句:

fn main() {
    let a = 3 - 5;
    assert_eq!(if a < 0 { 0 } else { a }, 0);
}

由于您有两个可以比较的值,您可能也对max感兴趣:

use std::cmp::max;

fn main() {
    assert_eq!(max(0, 3 - 5), 0);
}

您可以使您的建议语法有效,但我不确定它是否值得。提交时没有进一步评论......

fn main() {
    assert_eq!((3 - 5).but_if(|&v| v < 0).then(0), 0)
}

trait ButIf: Sized {
    fn but_if<F>(self, f: F) -> ButIfTail<Self>
        where F: FnOnce(&Self) -> bool;
}

// or `impl<T> ButIf for T {` for maximum flexibility
impl ButIf for i32 {
    fn but_if<F>(self, f: F) -> ButIfTail<Self>
        where F: FnOnce(&Self) -> bool,
    {
        ButIfTail(f(&self), self)
    }
}

struct ButIfTail<T>(bool, T);

impl<T> ButIfTail<T> {
    fn then(self, alt: T) -> T {
        if self.0 {
            alt
        } else {
            self.1
        }
    }
}

3
投票

更新:自从Rust 1.27添加Option::filter后,这有点好了:

assert_eq!(Some(3 - 5).filter(|&v| v >= 0).unwrap_or(0), 0);

在Rust 1.27之前,你需要一个迭代器才能编写一个单独的链式表达式而不需要额外的自定义机制:

assert_eq!(Some(3 - 5).into_iter().filter(|&v| v >= 0).next().unwrap_or(0), 0);
© www.soinside.com 2019 - 2024. All rights reserved.