tyname - Type names on stable Rust

| Docs | Crates.io | |:----------------:|:--------------------:| | docs | crates |

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.

Examples

Use

Works for every built-in type.

rust 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.

rust assert_eq!( type_name::<(i8, i16, i32, i64, i128)>(), String::from("(i8, i16, i32, i64, i128)") );

Works on structs.

rust 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.

rust assert_eq!( type_name::<fn(i32, f32) -> bool>(), String::from("fn(i32, f32) -> bool") ); assert_eq!( type_name::<fn()>(), String::from("fn() -> ()") );

Implement

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.

``rust /// The type we want to make work for theTypeName` trait struct Foo { a: T1, b: T2 }

/// The manual implementation. impl crate::TypeName for Foo where T1: TypeName, T2: TypeName, { fn writetypename(w: &mut W) -> std::fmt::Result where W: std::fmt::Write { w.writestr("Foo<")?; T1::writetypename(w)?; w.writestr(", ")?; T2::writetypename(w)?; w.write_char('>') } }

fn main() { asserteq!( typename::>(), String::from("Foo") ); } ```

Future

With a #[derive(TypeName)] functionality it will be possible to implement this for custom types such as the struct Foo above like the following.

```rust

[derive(TypeName)]

struct Foo{ a: T1, b: T2, } ```

Done.

Short comings

License

Licensed under either of

at your option.

Dual licence: badge badge

Contribution

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.