If statement 在折叠的内部使用if

If statement 在折叠的内部使用if,if-statement,rust,fold,If Statement,Rust,Fold,我需要计算bool向量的长度,i32,如果bool为真,则递增计数。我正在使用fold来实现这一点: fn main() { let domain = [(true, 1), (false, 2), (true, 3)]; let dom_count = domain.iter() .fold(0, |count, &(exists, _)| if exists {count + 1}); println!("dom_count: {}", dom

我需要计算bool向量的长度,i32,如果bool为真,则递增计数。我正在使用fold来实现这一点:

fn main() {
    let domain = [(true, 1), (false, 2), (true, 3)];
    let dom_count = domain.iter()
        .fold(0, |count, &(exists, _)| if exists {count + 1});
    println!("dom_count: {}", dom_count);
}
编辑抱怨说:

.fold0,| count,&exists,124;如果存在{count+1} ^^^^^^^^^^^^^^^^^^^^^应为,已找到整数变量 所以我加了一个,;得到这个:

.fold0,| count,&exists,124;如果存在{count+1;} ^^^^^^^^^^^^^^^^^^^^^^应为整数变量,已找到
如何在fold内部正确使用if语句?

当if条件为false时,您尝试使用什么值

这是编译器首先告诉你的。因为没有else子句,所以缺少的子句的返回类型必须为。由于if的true和false分支必须具有相同的类型,因此true分支必须返回。然而,真正的分支正在尝试返回一个数字

加入—;,使if的两个分支都返回,但失败了,因为折叠应该返回一个整数

一种解决方案是在else子句中返回一个值:

使用过滤器更为惯用:

并且Iterator::count已经处理了计算项目数的操作:


非常感谢。我不知道,如果语句的行为是这样的。我也为缺少MCVE道歉,我把它清理干净了。在一个相关的注释中,为什么Rust允许单行if语句缺失;如果它们没有返回值?例如,它count是一个变量,为什么要编译:如果为true{count=1}?是否应该要求您添加分号:if true{count=1;}?@HiDefender如果它们不返回值-它们确实返回值-类型的值。这是空元组,有时称为单位类型。
fn main() {
    let domain = [(true, 1), (false, 2), (true, 3)];

    let dom_count = domain.iter()
        .fold(0, |count, &(exists, _)| {
            if exists {
                count + 1
            } else {
                count
            }
        });

    println!("dom_count: {}", dom_count);
}
fn main() {
    let domain = [(true, 1), (false, 2), (true, 3)];

    let dom_count = domain.iter()
        .fold(0, |count, &(exists, _)| {
            count + if exists {
                1
            } else {
                0
            }
        });

    println!("dom_count: {}", dom_count);
}
fn main() {
    let domain = [(true, 1), (false, 2), (true, 3)];

    let dom_count = domain.iter()
        .filter(|&&(exists, _)| exists)
        .fold(0, |count, _| count + 1);

    println!("dom_count: {}", dom_count);
}
fn main() {
    let domain = [(true, 1), (false, 2), (true, 3)];

    let dom_count = domain.iter().filter(|&&(exists, _)| exists).count();

    println!("dom_count: {}", dom_count);
}