In C++, we can overload operator bool()
to convert a struct to bool
:
struct Example {
explicit operator bool() const {
return false;
}
};
int main() {
Example a;
if (a) { /* some work */ }
}
Can we do something simple (and elegant) in Rust so to:
pub struct Example {}
fn main() {
let k = Example {};
if k {
// some work
}
}
There's no direct equivalent of operator bool()
. A close alternative would be to implement From
(which will also implement Into
) and call the conversion explicitly:
pub struct Example;
impl From<Example> for bool {
fn from(_other: Example) -> bool {
false
}
}
fn main() {
let k = Example;
if k.into() {
// some work
}
}
This will take ownership of Example
, meaning you can't use k
after it's been converted. You could implement it for a reference (impl From<&Example> for bool
) but then the call site becomes uglier ((&k).into()
).
I'd probably avoid using From
/ Into
for this case. Instead, I'd create a predicate method on the type. This will be more readable and can take &self
, allowing you to continue using the value.
See also:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With