简体   繁体   中英

mapMulti equivalent in rust

Is there something similar to mapMulti in rust?

I have the following contrived example:

fn main() {
    let buf = vec![1,2,3,4,5];
    let mut sum = 0;
    
    // sum even numbers and 1 in buf (1+2+4)
    buf.iter().map(|x| {
        if x % 2 == 0 {
           (true, x)
        } else {
            if *x == 1 {
                (true, x)
            } else {
                (false, x)
            }
        }
    }).for_each(|(cond, n)| {
        if cond {
            sum += n;
        }
    });
    
    println!("sum: {:?}", sum);
}

output:

sum: 7

playground link

I would rather write something like this instead which is more concise:

fn main() {
    let buf = vec![1,2,3,4,5];
    let mut sum = 0;

    // sum even numbers and 1 in buf (1+2+4)
    buf.iter().map_multi(|(x, consumer)| {
        if x % 2 == 0 {
           consumer.accept(x);
        } else {
            if *x == 1 {
                consumer.accept(x)
            }
        }
    }).for_each(|n| {
        sum += n
    });

    println!("sum: {:?}", sum);
}

Is this possible using the standard library in rust?

To directly answer your question, filter_map does exactly what you asked for (by returning Some(x) instead of (true, x) and None instead of (false, x) . However I would write your code even more succinctly as such:

fn main() {
    let buf = vec![1, 2, 3, 4, 5];
    let even_or_one = buf.iter().filter(|&&n| n == 1 || n % 2 == 0);
    println!("sum: {:?}", even_or_one.sum::<i64>());
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM