Skip to content

Instantly share code, notes, and snippets.

@yohhoy
Created July 6, 2018 07:45
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save yohhoy/b921e1aad660dcd924cc8c9d0099b028 to your computer and use it in GitHub Desktop.
Save yohhoy/b921e1aad660dcd924cc8c9d0099b028 to your computer and use it in GitHub Desktop.
Numeric cast (as operator) in generics
trait FromU32 {
fn from_u32(v: u32) -> Self;
}
macro_rules! impl_from_u32 {
($($ty:ty)*) => {
$(
impl FromU32 for $ty {
#[inline]
fn from_u32(v: u32) -> $ty {
v as $ty
}
}
)*
}
}
impl_from_u32!(u8 u16 u32 u64 usize);
impl FromU32 for bool {
#[inline]
fn from_u32(v: u32) -> Self {
v != 0
}
}
fn f<T: FromU32>() -> Option<T>
{
let x: u32 = 42;
Some(FromU32::from_u32(x))
}
fn main() {
println!("{:?}", f::<bool>());
println!("{:?}", f::<u8>());
println!("{:?}", f::<u16>());
println!("{:?}", f::<u32>());
println!("{:?}", f::<u64>());
println!("{:?}", f::<usize>());
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment