Crates.io | tyname |
lib.rs | tyname |
version | 0.1.0 |
source | src |
created_at | 2018-11-27 15:32:11.631789 |
updated_at | 2018-11-27 15:32:11.631789 |
description | Retrieve type names during program execution on stable Rust. |
homepage | https://github.com/robbepop/tyname |
repository | https://github.com/robbepop/tyname |
max_upload_size | |
id | 98941 |
size | 28,335 |
Docs | Crates.io |
---|---|
WORKS ON STABLE RUST
Retrieve type names during program execution on stable Rust.
Other solutions in the Rust ecosystem use the unstable core::intrinsics::type_name
API.
Works for every built-in type.
assert_eq!(type_name::<()>(), String::from("()"));
assert_eq!(type_name::<i32>(), String::from("i32"));
assert_eq!(type_name::<[u8; 32]>(), String::from("[u8; 32]"));
Works for tuples up to 10 different fields.
assert_eq!(
type_name::<(i8, i16, i32, i64, i128)>(),
String::from("(i8, i16, i32, i64, i128)")
);
Works on structs.
assert_eq!(
type_name::<Vec<u8>>(), String::from("Vec<u8>")
);
assert_eq!(
type_name::<Result<i32, String>>(),
String::from("Result<i32, String>")
);
Works on function pointer types.
assert_eq!(
type_name::<fn(i32, f32) -> bool>(),
String::from("fn(i32, f32) -> bool")
);
assert_eq!(
type_name::<fn()>(),
String::from("fn() -> ()")
);
The TypeName
trait is used for retrieving the names.
Every type that implements it can be used.
This library already implements the most common types for the users
Users can implement it manually for their own types, too.
Note: A derive functionality is planned but not yet crafted.
/// The type we want to make work for the `TypeName` trait
struct Foo<T1, T2> { a: T1, b: T2 }
/// The manual implementation.
impl<T1, T2> crate::TypeName for Foo<T1, T2>
where
T1: TypeName,
T2: TypeName,
{
fn write_type_name<W>(w: &mut W) -> std::fmt::Result
where
W: std::fmt::Write
{
w.write_str("Foo<")?;
T1::write_type_name(w)?;
w.write_str(", ")?;
T2::write_type_name(w)?;
w.write_char('>')
}
}
fn main() {
assert_eq!(
type_name::<Foo<bool, char>>(),
String::from("Foo<bool, char>")
);
}
With a #[derive(TypeName)]
functionality it will be possible to implement this
for custom types such as the struct Foo
above like the following.
#[derive(TypeName)]
struct Foo<T1, T2>{
a: T1,
b: T2,
}
Done.
#[derive(TypeName)]
functionality provided, yet.core::intrinsics::type_name
APIstd::result::
in std::result::Result<T, E>
.fn()
will print fn() -> ()
instead.Licensed under either of
at your option.
Unless you explicitly state otherwise, any contribution intentionally submitted for inclusion in the work by you, as defined in the Apache-2.0 license, shall be dual licensed as above, without any additional terms or conditions.