# From\<bool\> for primitive integer types

**URL:** <https://internals.rust-lang.org/t/from-bool-for-primitive-integer-types/7464>\
**Category:** libs\
**Created:** [May 7, 2018, 6:34pm UTC](https://internals.rust-lang.org/t/from-bool-for-primitive-integer-types/7464 "2018-05-07T18:34:17Z")\
**Posts on this page:** 20\
**Page:** 1

<div class="post-metadata">

**Author:** ![ithinuel](https://sea2.discourse-cdn.com/flex002/user_avatar/internals.rust-lang.org/ithinuel/32/3233_2.png) [@ithinuel](https://internals.rust-lang.org/u/ithinuel)\
**Post date:** [May 7, 2018, 6:34pm UTC](https://internals.rust-lang.org/t/from-bool-for-primitive-integer-types/7464/1 "2018-05-07T18:34:17Z")

</div>

Hi all,

It has probably already been discussed somewhere but I can’t find anything on this forum nor on google.

Is there any reason why `From<bool>` is not implemented for all integer types (signed & unsigned) ?

Kind regards

---

<div class="post-metadata">

**Author:** ![scottmcm](https://sea2.discourse-cdn.com/flex002/user_avatar/internals.rust-lang.org/scottmcm/32/2355_2.png) [@scottmcm](https://internals.rust-lang.org/u/scottmcm)\
**Post date:** [May 7, 2018, 9:41pm UTC](https://internals.rust-lang.org/t/from-bool-for-primitive-integer-types/7464/2 "2018-05-07T21:41:11Z")

</div>

It’s lossless and works through `as`, so having it in `From` sure sounds reasonable to me.

Maybe just make a PR and see what libs says?

---

<div class="post-metadata">

**Author:** ![ithinuel](https://sea2.discourse-cdn.com/flex002/user_avatar/internals.rust-lang.org/ithinuel/32/3233_2.png) [@ithinuel](https://internals.rust-lang.org/u/ithinuel)\
**Post date:** [May 7, 2018, 9:59pm UTC](https://internals.rust-lang.org/t/from-bool-for-primitive-integer-types/7464/3 "2018-05-07T21:59:46Z")

</div>

Indeed, I’m already preparing it 🙂

---

<div class="post-metadata">

**Author:** ![H2CO3](https://sea2.discourse-cdn.com/flex002/user_avatar/internals.rust-lang.org/h2co3/32/2849_2.png) [@H2CO3](https://internals.rust-lang.org/u/H2CO3)\
**Post date:** [May 8, 2018, 5:38am UTC](https://internals.rust-lang.org/t/from-bool-for-primitive-integer-types/7464/4 "2018-05-08T05:38:07Z")

</div>

Sounds right, since wider integer types already implement `From<narrower_integer_type>` too.

---

<div class="post-metadata">

**Author:** ![GolDDranks](https://sea2.discourse-cdn.com/flex002/user_avatar/internals.rust-lang.org/golddranks/32/1158_2.png) [@GolDDranks](https://internals.rust-lang.org/u/GolDDranks)\
**Post date:** [May 8, 2018, 6:25am UTC](https://internals.rust-lang.org/t/from-bool-for-primitive-integer-types/7464/5 "2018-05-08T06:25:27Z")

</div>

I was trying to find a counterargument; `bool` isn’t exactly an integer type, semantically speaking, so how can one canonically map true and false to integers, except by convention (false = 0, true = 1).

However, I failed to convince myself that any other mapping would do because of the ring isomorphism to u1: addition = XOR and multiplication = AND. So there’s only one mapping that makes sense, and that mapping is lossless, plus calling `.into()`, is explicit. I’m out of arguments. Do it.

---

<div class="post-metadata">

**Author:** ![DanielKeep](https://sea2.discourse-cdn.com/flex002/user_avatar/internals.rust-lang.org/danielkeep/32/1332_2.png) [@DanielKeep](https://internals.rust-lang.org/u/DanielKeep)\
**Post date:** [May 8, 2018, 6:55am UTC](https://internals.rust-lang.org/t/from-bool-for-primitive-integer-types/7464/6 "2018-05-08T06:55:34Z")

</div>

There are three potential mappings: true/false =\> 1/0, 0/1, -1/0. Four if you count 1/0/FileNotFound.

Conceptual shortcuts make it easier to make conceptual mistakes.

---

<div class="post-metadata">

**Author:** ![scottmcm](https://sea2.discourse-cdn.com/flex002/user_avatar/internals.rust-lang.org/scottmcm/32/2355_2.png) [@scottmcm](https://internals.rust-lang.org/u/scottmcm)\
**Post date:** [May 8, 2018, 7:21am UTC](https://internals.rust-lang.org/t/from-bool-for-primitive-integer-types/7464/7 "2018-05-08T07:21:04Z")

</div>

@DanielKeep: As @GolDDranks points out, only two of those are consistent with the fact that `|` and `&` work on `bool` as a 1-bit number: 1/0 or -1/0.

But it’s all academic anyway, since the `as` operator already defines the meaning of the conversion.

---

<div class="post-metadata">

**Author:** ![DanielKeep](https://sea2.discourse-cdn.com/flex002/user_avatar/internals.rust-lang.org/danielkeep/32/1332_2.png) [@DanielKeep](https://internals.rust-lang.org/u/DanielKeep)\
**Post date:** [May 8, 2018, 7:32am UTC](https://internals.rust-lang.org/t/from-bool-for-primitive-integer-types/7464/8 "2018-05-08T07:32:57Z")

</div>

But `as` defines narrowing conversions, so by that logic, `From<u64> for u8` should also be implemented. I’m not saying `From<bool> for {integer}` should disagree with `as`; I don’t think `bool as {integer}` is a _particularly_ good conversion in the first place, so I don’t think it makes the best argument for defining a `From` implementation in this case.

---

<div class="post-metadata">

**Author:** ![kornel](https://sea2.discourse-cdn.com/flex002/user_avatar/internals.rust-lang.org/kornel/32/2711_2.png) [@kornel](https://internals.rust-lang.org/u/kornel)\
**Post date:** [May 8, 2018, 4:58pm UTC](https://internals.rust-lang.org/t/from-bool-for-primitive-integer-types/7464/9 "2018-05-08T16:58:14Z")

</div>

I’m not sure about this. Bool isn’t a regular number. It has meaning beyond `u1`, so this conversion could hide bugs, e.g. if you thought a function returns a value, but it only reports success:

```rust
let bytes_written: u64 = write(stuff).into();

```

---

<div class="post-metadata">

**Author:** ![ithinuel](https://sea2.discourse-cdn.com/flex002/user_avatar/internals.rust-lang.org/ithinuel/32/3233_2.png) [@ithinuel](https://internals.rust-lang.org/u/ithinuel)\
**Post date:** [May 8, 2018, 5:18pm UTC](https://internals.rust-lang.org/t/from-bool-for-primitive-integer-types/7464/10 "2018-05-08T17:18:47Z")

</div>

Then should’nt this API use a `Result<(), ()>` rather than a boolean ?

---

<div class="post-metadata">

**Author:** ![kornel](https://sea2.discourse-cdn.com/flex002/user_avatar/internals.rust-lang.org/kornel/32/2711_2.png) [@kornel](https://internals.rust-lang.org/u/kornel)\
**Post date:** [May 8, 2018, 5:30pm UTC](https://internals.rust-lang.org/t/from-bool-for-primitive-integer-types/7464/11 "2018-05-08T17:30:36Z")

</div>

It should, but not all APIs are like that. Also Result is noisy and may be annoying for calls where it’s not critical to check (eg write to stderr was such case, eprintln doesn’t report now)

---

<div class="post-metadata">

**Author:** ![ithinuel](https://sea2.discourse-cdn.com/flex002/user_avatar/internals.rust-lang.org/ithinuel/32/3233_2.png) [@ithinuel](https://internals.rust-lang.org/u/ithinuel)\
**Post date:** [May 8, 2018, 7:19pm UTC](https://internals.rust-lang.org/t/from-bool-for-primitive-integer-types/7464/12 "2018-05-08T19:19:33Z")

</div>

My initial incentive for that question is because we often have to extract bits from integer while working on embedded targets. Writing generic for becomes tedious when a function should insert/extract from a register the in the same way for all fields.

It can be worked around with [a _newtype_](https://play.rust-lang.org/?gist=53ef537ce6ae63231c53bed9fc2da383&version=stable&mode=debug) :

```rust
use std::convert::From;
use std::convert::Into;

struct MyBool(bool);
impl From<bool> for MyBool {
    fn from(v: bool) -> MyBool {
        MyBool(v)
    }
}
impl Into<u32> for MyBool {
    fn into(self) -> u32 {
        self.0 as u32
    }
}

fn do_something<T>(v: T) where T: Into<u32> {
    let u: u32 = v.into();
    println!("{}", u);
}

fn main() {
    do_something(MyBool::from(true));
}

```

But I don’t find it really elegant.

---

<div class="post-metadata">

**Author:** ![matklad](https://sea2.discourse-cdn.com/flex002/user_avatar/internals.rust-lang.org/matklad/32/12266_2.png) [@matklad](https://internals.rust-lang.org/u/matklad)\
**Post date:** [May 8, 2018, 8:43pm UTC](https://internals.rust-lang.org/t/from-bool-for-primitive-integer-types/7464/13 "2018-05-08T20:43:28Z")

</div>

> [@GolDDranks](#):
>
> bool isn’t exactly an integer type, semantically speaking,

> [@kornel](#):
>
> Bool isn’t a regular number.

Note that Python, which is considered to be a strongly-typed dynamically typed language, bool is, in fact, a number:

```rust
>>> import numbers
>>> isinstance(True, numbers.Number)
True
>>> True + True
2
>>>

```

I don't think that this causes any problems, and can be sometimes useful.

---

<div class="post-metadata">

**Author:** ![scottmcm](https://sea2.discourse-cdn.com/flex002/user_avatar/internals.rust-lang.org/scottmcm/32/2355_2.png) [@scottmcm](https://internals.rust-lang.org/u/scottmcm)\
**Post date:** [May 8, 2018, 10:30pm UTC](https://internals.rust-lang.org/t/from-bool-for-primitive-integer-types/7464/14 "2018-05-08T22:30:32Z")

</div>

> [@DanielKeep](#):
>
> But as defines narrowing conversions, so by that logic, From\<u64\> for u8 should also be implemented.

Which is why I explicitly also said "It's lossless", so no, it's not "by that logic".

---

<div class="post-metadata">

**Author:** ![marcianx](https://sea2.discourse-cdn.com/flex002/user_avatar/internals.rust-lang.org/marcianx/32/3249_2.png) [@marcianx](https://internals.rust-lang.org/u/marcianx)\
**Post date:** [May 9, 2018, 1:57am UTC](https://internals.rust-lang.org/t/from-bool-for-primitive-integer-types/7464/15 "2018-05-09T01:57:00Z")

</div>

> [@ithinuel](#):
>
> ```rust
> do_something(MyBool::from(true));
> 
> ```

Why not just: `do_something(true as u32);`? It's not bad that `as` is used for non-obvious primitive conversions.

> [@matklad](#):
>
> \>\>\> True + True 2

Wow. That's quite the contrast from theory, given that boolean algebra has 1+1=1 since + acts as the OR operator.

---

<div class="post-metadata">

**Author:** ![scottmcm](https://sea2.discourse-cdn.com/flex002/user_avatar/internals.rust-lang.org/scottmcm/32/2355_2.png) [@scottmcm](https://internals.rust-lang.org/u/scottmcm)\
**Post date:** [May 9, 2018, 2:04am UTC](https://internals.rust-lang.org/t/from-bool-for-primitive-integer-types/7464/16 "2018-05-09T02:04:05Z")

</div>

> [@marcianx](#):
>
> Why not just: do\_something(true as u32);?

> **[Clippy Lints](https://rust-lang-nursery.github.io/rust-clippy/master/index.html#cast_lossless)**
>
> A collection of lints to catch common mistakes and improve your Rust code.

---

<div class="post-metadata">

**Author:** ![ithinuel](https://sea2.discourse-cdn.com/flex002/user_avatar/internals.rust-lang.org/ithinuel/32/3233_2.png) [@ithinuel](https://internals.rust-lang.org/u/ithinuel)\
**Post date:** [May 9, 2018, 5:35am UTC](https://internals.rust-lang.org/t/from-bool-for-primitive-integer-types/7464/17 "2018-05-09T05:35:00Z")

</div>

> [@marcianx](#):
>
> Why not just: do\_something(true as u32);

It is an example where you cannot assume what type will be used internally by `do_something`.

And this does not compile :

```rs
fn do_something<T>(v: T) {
    println!("{}", v as u32);
}

fn main() {
    do_something(true);
}

```

---

<div class="post-metadata">

**Author:** ![marcianx](https://sea2.discourse-cdn.com/flex002/user_avatar/internals.rust-lang.org/marcianx/32/3249_2.png) [@marcianx](https://internals.rust-lang.org/u/marcianx)\
**Post date:** [May 9, 2018, 12:59pm UTC](https://internals.rust-lang.org/t/from-bool-for-primitive-integer-types/7464/18 "2018-05-09T12:59:10Z")

</div>

> [@scottmcm](#):
>
> [Redirecting to https://rust-lang.github.io/rust-clippy/master](https://rust-lang-nursery.github.io/rust-clippy/master/index.html#cast_lossless)

Sorry, the actual point I failed to emphasize was that if you have a function with generic type `T: Into<u64>`, you can just pass in a `u64`, as the conversion is trivial to write caller-side (`b as u64`). The use of `as` is almost beside the point, but it's easier to defend in this case since the conversion is not lossy. A clearer alternative might be to make a more descriptive helper method or inline its trivial implementation:

```rust
fn one_if_true(b: bool): u64 { if b {1} else {0} }
...
do_something(one_if_true(true));
do_something(if b {1} else {0});

```

Generally, an implementation of `Into` is useful when the intended conversion is obvious (and especially so if its implementation is non-trivial). I agree with @DanielKeep's original comment: mathematically speaking, there's not an obvious canonical choice for conversion from `bool`, although some languages have settled on `false`/`true` -\> `0`/`1`.

> [@ithinuel](#):
>
> ```rust
> fn do_something<T>(v: T) {
> println!("{}", v as u32);
> }
> 
> fn main() {
> do_something(true);
> }
> 
> ```
> 
> It is an example where you cannot assume what type will be used internally by do\_something.

This example has no constraints on `T` at all, making `v` unusable within the body. My point is, if you have `T: Into<u64>` on the method, just pass in `u64` by doing an explicit conversion client-side as that's trivial for `bool`s given a choice of numbers for `true` and `false`.

---

<div class="post-metadata">

**Author:** ![ithinuel](https://sea2.discourse-cdn.com/flex002/user_avatar/internals.rust-lang.org/ithinuel/32/3233_2.png) [@ithinuel](https://internals.rust-lang.org/u/ithinuel)\
**Post date:** [May 9, 2018, 1:09pm UTC](https://internals.rust-lang.org/t/from-bool-for-primitive-integer-types/7464/19 "2018-05-09T13:09:41Z")

</div>

If this can be of any help, [this](https://play.rust-lang.org/?gist=e669ae6d9695ca933f5dce42e03a6eae&version=nightly&mode=debug) is the usecase that’s driving my reflection.

I have a macro that generates function that needs to convert between some types (that might be `bool`) to some primitive integer type. If you uncomment line 216 everything breaks simply because bool does not implement from and you cannot implemented it (trait & type defined in another crate).

---

<div class="post-metadata">

**Author:** ![marcianx](https://sea2.discourse-cdn.com/flex002/user_avatar/internals.rust-lang.org/marcianx/32/3249_2.png) [@marcianx](https://internals.rust-lang.org/u/marcianx)\
**Post date:** [May 9, 2018, 2:34pm UTC](https://internals.rust-lang.org/t/from-bool-for-primitive-integer-types/7464/20 "2018-05-09T14:34:44Z")

</div>

Thanks, that makes your use-case (and the workaround strategy) clearer. Perhaps you are already aware of this solution, but in case you didn’t try it: you can work around the omission of `From<bool> for u32` by adding an extension trait as follows.

```rust
trait IntoU32 {
  into_u32(&self): u32;
}

impl<T: Into<u32>> IntoU32 for T {
  into_u32(&self): u32 { self.into() };
}

impl IntoU32 for bool {
  into_u32(&self): u32 { self as u32 };
}

```

and using `into_u32()` instead of `into()` everywhere. Since `IntoU32` is local to your crate, it has the semantics that make most sense for your specific crate for `bool -> u32` conversion.

[Next page](https://internals.rust-lang.org/t/from-bool-for-primitive-integer-types/7464.md?page=2)
