serde_type_name

Crates.ioserde_type_name
lib.rsserde_type_name
version0.2.0
sourcesrc
created_at2018-08-24 18:29:27.896996
updated_at2019-02-24 11:01:07.624975
descriptionlookup name of type for any struct or enum that derives serde Serialize
homepagehttps://github.com/mmrath/serde_type_name
repository
max_upload_size
id81142
size23,693
publish (github:yaws-rs:publish)

documentation

README

Build Status Current Crates.io Version

Serde Type Name

Serde Type Name - lookup name of type for any struct or enum that derives serde Serialize. This is completely based on

https://stackoverflow.com/questions/46612327/using-serde-to-get-a-types-name-as-string-when-the-type-is-only-serialize

Usage

extern crate serde_type_name;
extern crate serde;
#[macro_use]
extern crate serde_derive;

use serde::Serialize;
use serde_type_name::type_name;

#[derive(Serialize)]
enum SimpleEnum {
    A(i32),
    B,
    C { code: i32 },
}

#[derive(Serialize)]
struct SimpleStruct {
    pub a: i32,
}

#[derive(Serialize)]
struct GenericStruct<T: Serialize> {
    pub inner: T,
}

fn main() {
    assert_eq!("SimpleEnum", type_name(&SimpleEnum::A(10)).unwrap());
    assert_eq!("SimpleEnum", type_name(&SimpleEnum::B).unwrap());
    assert_eq!("SimpleEnum", type_name(&SimpleEnum::C { code: 32 }).unwrap());
    
    assert_eq!("SimpleStruct", type_name(&SimpleStruct { a: 20 }).unwrap());
    
    let gs = GenericStruct { inner: 32 };
    assert_eq!("GenericStruct", type_name(&gs).unwrap());
    
    let gs_enum = GenericStruct {
        inner: SimpleEnum::B,
    };
    assert_eq!("GenericStruct", type_name(&gs_enum).unwrap());
    assert_eq!("SimpleEnum", type_name(&gs_enum.inner).unwrap());
}
Commit count: 0

cargo fmt