What is an idiomatic way of looping with a match when I only care about one variant and not even the value in the variant?

Viewed 295
loop {
    match stream.write(&buffer) {
        Ok(_) => break,
        _ => {}
    }
}

Is there a way to write it on a more readable/idiomatic way? I don't need to do anything inside the match, I don't need any actions after the Ok or after the Err, because the buffer is updated as a reference whenever it returns Ok.

Something like:

while match some_fn() != Ok() {
    ...
}
2 Answers

The general case is covered by ForceBru's answer, but since you have a Result and don't care about the value inside Ok, you can use Result::is_ok (or Result::is_err):

while stream.write(&buffer).is_err() {}

As pointed out by rodrigo in the comments:

Worth noting that Rust 1.42 adds the matches! macro, so you can write while matches!(stream.write(&buffer), Ok(_)) {}, useful for other enums that lack the is_* functions.

You can use while let:

fn some_fn(x: u32) -> Option<u32> {
    if x > 30 {
        Some(x)
    } else {
        None
    }
} 

fn main() {
    let mut x = 0;
    while let None = some_fn(x) {
        x += 1;
    }
    
    dbg!(x);
}

Playground

Same with the Result type: check if some_fn returned Err.

Related