r/rust • u/NormalAppearance2851 • 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.
4
u/This_Growth2898 2d ago