How to use as bool for numbers?

Hello,
Why does the following code give an error:

fn main() {
    print!("{} {}", 1 as bool, 0 as bool);
}

Thank you.

Because integers have more possible values. What should 2 as bool yield?

If you want to test whether a number is zero, then just compare it to zero.

2 Likes

Here's a list of conversions allowed using as operator.

https://doc.rust-lang.org/stable/reference/expressions/operator-expr.html#type-cast-expressions

You can see there's no integer to boolean conversion in it.

1 Like

Hello,
Anything other than zero should be considered as true.

You write this “conversion” as x != 0 :wink:

9 Likes

Hello,
Thanks again.

fn main() {
    print!("{} {}", true as bool, false as bool);
}

From Beginning Rust: Get Started with Rust 2021 Edition 2nd ed. Edition by Carlo Milanesi book:

But you cannot use the “as bool” clause with a number, because not every numeric
value corresponds to a Boolean; in fact only zero and one have this property, so in
general such a conversion would not be well defined.

1 Like

Is the question here why true as bool compiles successfully? Going by the reference page that was already linked above, it’s because

as can be used to explicitly perform coercions, as well as the following additional casts.

And among the types of coercions, we have

  • T to U if T is a subtype of U (reflexive case)

which includes the case that you convert a value of some type T to the same type T itself.

3 Likes