Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Code shared from the Rust Playground
#![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
You can’t perform that action at this time.