Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Expected bool, found i32 when using the operator %

Tags:

rust

Maybe this is normal behavior, but someone can help me with this:

trait Flujo<T: std::clone::Clone> {
    fn filter<F: Fn(T)->bool>(&self, prot: F);
}   

impl<T: std::clone::Clone> Flujo<T> for Test<T> {
     fn filter<F: Fn(T)->bool>(&self, prot: F ){ 
     ..//
     }
}

in this simple test works

test.filter(|x| -> bool{ 

    true
});

but when I try this

test.filter(|x| -> bool{ 
    //return x % 2 ? true : false;

    if x % 2 {   <-- Error
      return true;            
    } else{
      return false;
    }
});

Error:

mismatched types:
 expected `bool`,
    found `i32` [E0308]
if value % 2 {
   ^~~~~~~~~

I searched and read, but the second link not quite understand, can someone explain me why this fails.

https://doc.rust-lang.org/reference.html#arithmetic-operators

https://doc.rust-lang.org/std/ops/trait.Rem.html


Update:

You can see with this test, it is not the same code, but the same error is obtained:

play.rust

like image 387
Angel Angel Avatar asked Aug 11 '26 17:08

Angel Angel


1 Answers

In C, C++ and probably other languages, integers can be implicitly converted to booleans. That's not the case in Rust: Rust will never perform implicit conversions between primitive types (whether it's integer to integer, integer to float, integer to boolean, etc.), in order to avoid surprises.

All you need to do is add != 0 to the expression that evaluates to an integer (you may need to add parentheses to get the correct operator precedence) to turn it into a boolean expression that behaves like in C or C++.

test.filter(|x| -> bool { 
    if x % 2 != 0 {
      return true;
    } else {
      return false;
    }
});

or just:

test.filter(|x| x % 2 != 0);
like image 133
Francis Gagné Avatar answered Aug 13 '26 17:08

Francis Gagné



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!