Skip to content

Instantly share code, notes, and snippets.

@peterjoel
Last active March 6, 2019 09:38
Show Gist options
  • Save peterjoel/a808efe76286a406b05e7d303ba6ef02 to your computer and use it in GitHub Desktop.
Save peterjoel/a808efe76286a406b05e7d303ba6ef02 to your computer and use it in GitHub Desktop.
Two possible implementations of a safe wrapper around `core::intrinsics::type_name`
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));
}
#![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>()
}
}
#![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