From<bool> for primitive integer types

That completely defeats the point of the "Into trick", though. One could just as well say "the conversion is trivial to write caller-side (b.into())".

As the lint description says,

Using the conversion functions prevents conversions from turning into silent lossy conversions if the types of the input expressions ever change, and make it easier for people reading the code to know that the conversion is lossless.

1 Like

Indeed, @marcianx I could even create a trait MyFrom<T> that I would use instead of From<T>. But then I’d have to also replace everything that uses From/Into internally.

It would be cumbersome and not very nice to user of the crate/framework.

My point was that given that there's no mathematically canonical conversion from bool to u64, there was still a workaround for OP's use-case, but see my response to him below about a mistake I made.

Sorry, I wasn't specific enough about how exactly this would be used. I meant that you would introduce something like IntoU32 (updated below) in your crate and use it only within your crate. External users of your crate would still use the standard TryFrom and From traits and your IntoU32 trait would automatically be implemented for those due to the default implementation and be used only within your macros. The user of your crate wouldn't need to care about its existence.

#![feature(specialization)]

trait IntoU32: Sized {
    fn into_u32(self) -> u32;
}

impl<T: Into<u32>> IntoU32 for T {
    default fn into_u32(self) -> u32 { self.into() }
}

impl IntoU32 for bool {
    fn into_u32(self) -> u32 { if self {1} else {0} }
}

BUT while I started to modify your playground example to demonstrate this, I realized that specialization doesn't work in this case: the Into<u32> bound on the first/default implementation means that the bool implementation is not a strict specialization and I get a conflicting implementation error (playground). Bah humbug...

So yes, sorry my solution was incorrect and I can't think of any way to transparently support types implementing the standard From/TryFrom while also supporting boolean conversion.

1 Like

I created the PR : https://github.com/rust-lang/rust/pull/50597

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.