Created
August 25, 2019 04:26
-
-
Save rust-play/c9f4cfaba00ec0fb116ae00e3bd13925 to your computer and use it in GitHub Desktop.
Code shared from the Rust Playground
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
#![feature(specialization)] | |
use std::any::type_name; | |
fn main(){ | |
let _:String=false.cast(); | |
let _:u32=0u8.cast(); | |
} | |
impl As<String> for bool{ | |
fn as_(self)->String{ | |
if self { "true" }else{ "false" }.into() | |
} | |
} | |
pub trait Cast<T> { | |
fn cast(self) -> T; | |
} | |
pub trait As<T> { | |
fn as_(self) -> T; | |
} | |
pub struct True; | |
pub struct False; | |
pub trait DoesItImplInto<T>{ | |
type DoesIt; | |
} | |
default impl<This,T> DoesItImplInto<T> for This{ | |
type DoesIt=False; | |
} | |
impl<This,T> DoesItImplInto<T> for This | |
where | |
This:Into<T>, | |
{ | |
type DoesIt=True; | |
} | |
pub trait CastInner<ImplsInto,T>{ | |
fn _cast_inner(self) -> T; | |
} | |
impl<This,T> CastInner<True,T> for This | |
where | |
This:Into<T>, | |
{ | |
fn _cast_inner(self) -> T{ | |
println!("{}:Into<{}>",type_name::<This>(),type_name::<T>()); | |
self.into() | |
} | |
} | |
impl<This,T> CastInner<False,T> for This | |
where | |
This:As<T>, | |
{ | |
fn _cast_inner(self) -> T{ | |
println!("{}:As<{}>",type_name::<This>(),type_name::<T>()); | |
self.as_() | |
} | |
} | |
impl<X, T> Cast<T> for X | |
where | |
X: DoesItImplInto<T>, | |
X: CastInner< | |
<X as DoesItImplInto<T>>::DoesIt, | |
T, | |
> | |
{ | |
fn cast(self) -> T { | |
CastInner::_cast_inner(self) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment