Created
July 6, 2018 07:45
-
-
Save yohhoy/b921e1aad660dcd924cc8c9d0099b028 to your computer and use it in GitHub Desktop.
Numeric cast (as operator) in generics
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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