Idiomatic way to just return Err() on expression evaluation to false

69 views Asked by At

All what I'm looking for is to have one-liner like:

assert!( 1 == 2 );

but instead of panic, want to just return MyErr().

For now I implement this way:

(1==2).then(|| ()).ok_or(MyErr())?;

Is there a cleaner way to do the same?

2

There are 2 answers

0
Dimitris Fasarakis Hilliard On

As @Krish mentioned, use an if statement here. For reference, this is also what bool.then basically does:

pub fn then<T, F: FnOnce() -> T>(self, f: F) -> Option<T> {
    if self { Some(f()) } else { None }
}
0
ppmag On

Looks like for now the best option is:

if !(1==2) { return Err() }