Rust: Result::ok_unit() to make Result<T, E> to Resutl<(), E>?

Created on 28 Dec 2019  路  4Comments  路  Source: rust-lang/rust

Sometimes people only care about the Error case and ignore the Ok value.

I see some code do something like:

use std::{fs, io};
use std::path::Path;
pub fn foo(a: &Path, b: &Path) -> io::Result<()> {
    fs::copy(a, b).map(|_| ())
}

Which I think is not really beautiful.

I proposed that we could add a method to Result to make that intent clearer:

impl<T, E> Result<T, E> {
    pub fn ok_unit(self) -> Result<(), E> {
        match self {
            Ok(_) => Ok(()),
            Err(e) => Err(e),
        }
    }
}

We could also name it Result::drop_ok or so.


Of course that just my own opinion. So I open to discussion.

C-feature-request T-libs

Most helpful comment

toilet closure

What a name :D ?

All 4 comments

.map(drop) also works and is arguably clearer than the toilet closure

toilet closure

What a name :D ?

toilet closure

What a name :D ?

https://users.rust-lang.org/t/twir-quote-of-the-week/328/721?u=dutchghost It comes from there

Maybe a clippy lint is better. I opened https://github.com/rust-lang/rust-clippy/issues/5001 for discussion.

Was this page helpful?
0 / 5 - 0 ratings