Last active
March 6, 2019 09:38
-
-
Save peterjoel/a808efe76286a406b05e7d303ba6ef02 to your computer and use it in GitHub Desktop.
Two possible implementations of a safe wrapper around `core::intrinsics::type_name`
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
fn main() { | |
println!("type = {:?}", debug::type_name::<String>()); | |
let v = vec![Some(Box::new(|s: i32| println!("{:?}", s)))]; | |
println!("type = {:?}", debug::type_name_of_val(&v)); | |
} |
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(core_intrinsics)] | |
pub mod debug { | |
use std::fmt; | |
pub struct TypeName { | |
inner: &'static str, | |
} | |
impl fmt::Debug for TypeName { | |
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { | |
write!(f, "{:?}", self.inner) | |
} | |
} | |
pub fn type_name<T: Sized>() -> TypeName { | |
TypeName { | |
inner: unsafe { core::intrinsics::type_name::<T>() } | |
} | |
} | |
pub fn type_name_of_val<T: Sized>(_: &T) -> TypeName { | |
type_name::<T>() | |
} | |
} |
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(core_intrinsics)] | |
pub mod debug { | |
use std::fmt; | |
use std::marker::PhantomData; | |
pub struct TypeName<T: ?Sized> { | |
marker: PhantomData<T>, | |
} | |
impl<T: ?Sized> fmt::Debug for TypeName<T> { | |
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { | |
f.write_str(unsafe { core::intrinsics::type_name::<T>() }) | |
} | |
} | |
pub fn type_name<T: Sized>() -> TypeName<T> { | |
TypeName { | |
marker: PhantomData, | |
} | |
} | |
pub fn type_name_of_val<T: Sized>(_: &T) -> TypeName<T> { | |
type_name::<T>() | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment