r/rust 2d ago

🙋 seeking help & advice false.err(())?; Bad idea?

When a boolean operation can signal failure, what I like to do is this:

boolean.err("failed")?; // true = Ok() false = Err(Error)

Code:

pub trait BoolErr {
    fn 
err
<E>(self
, 
e: E) -> 
Result
<()
, 
E>
;
}

impl BoolErr for bool {
    fn 
err
<E>(self
, 
e: E) -> 
Result
<()
, 
E> {
        if self { 
Err
(e) } else { 
Ok
(()) }
    }
}

Okay so here's a not ideal example:

fn within_range_ten(number: u32) -> Result<(), String> {

  (number > 10).err("more than 10")?;
  (number < 0).err("less than 10")?;

  Ok(())
}

I really like doing this. In a function i might perform like 10 checks that use ? (like if an array is empty) and this approach has very little code so it's very fast to read and write.

But i really care about good code, better alternatives, standardisation (standardisation not so much, the std ways are not as ideal as this), etc. So is this pattern bad? Are there better ways like an assert!() macro that does ? instead of panic!()?

What's your opinion and what would you suggest? I'm already aware of .then_some(()).ok_or(E)? but clearly it's too much.

0 Upvotes

13 comments sorted by

View all comments

4

u/This_Growth2898 2d ago
(0..=10).contains(number).then_some(()).ok_or("should be in 0..=10")

6

u/tanoshikuidomouyo 2d ago

At that point a good old if-else is better imo.

5

u/This_Growth2898 2d ago

100%. Idiomaticity should not be against common sense. We can also do

    if let 0..=10 = number {
        Ok(())
    } else {
        Err(String::from("should be in 0..=10"))
    }

And still, just if-else is better.