Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a Rust equivalent to C++'s operator bool() to convert a struct into a boolean?

Tags:

rust

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
    }
}
like image 712
Rahn Avatar asked Dec 01 '22 08:12

Rahn


1 Answers

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:

  • When should I implement std::convert::From vs std::convert::Into?
like image 152
Shepmaster Avatar answered Jun 10 '23 22:06

Shepmaster