我需要一个返回类型名称的函数,我有这个使用 serde 工作的函数,但现在我需要一个不需要类型的替代版本,Deserialize
以便我可以在具有借用成员的结构上使用它。
我怎样才能重写这个函数,以便它在类型为时工作Serialize
,但不是Deserialize
?
#[macro_use]
extern crate serde;
#[macro_use]
extern crate serde_derive;
use serde::de::{self, Deserialize, Deserializer, Visitor};
use std::fmt::{self, Display};
fn type_name<'de, D: Deserialize<'de>>() -> &'static str {
#[derive(Debug)]
struct NoError;
impl std::error::Error for NoError {
fn description(&self) -> &str {
"no error"
}
}
impl Display for NoError {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "NoError")
}
}
impl de::Error for NoError {
fn custom<T: Display>(_msg: T) -> Self {
NoError
}
}
struct NameDeserializer(Option<&'static str>);
impl<'a, 'de> Deserializer<'de> for &'a mut NameDeserializer {
type Error = NoError;
fn deserialize_any<V>(self, _visitor: V) -> Result<V::Value, Self::Error>
where V: Visitor<'de>
{
Err(NoError)
}
fn deserialize_unit_struct<V>(self, name: &'static str, _visitor: V) -> Result<V::Value, Self::Error>
where V: Visitor<'de>
{
self.0 = Some(name);
Err(NoError)
}
fn deserialize_newtype_struct<V>(self, name: &'static str, _visitor: V) -> Result<V::Value, Self::Error>
where V: Visitor<'de>
{
self.0 = Some(name);
Err(NoError)
}
fn deserialize_tuple_struct<V>(self, name: &'static str, _len: usize, _visitor: V) -> Result<V::Value, Self::Error>
where V: Visitor<'de>
{
self.0 = Some(name);
Err(NoError)
}
fn deserialize_struct<V>(self, name: &'static str, _fields: &'static [&'static str], _visitor: V) -> Result<V::Value, Self::Error>
where V: Visitor<'de>
{
self.0 = Some(name);
Err(NoError)
}
forward_to_deserialize_any! {
bool i8 i16 i32 i64 u8 u16 u32 u64 f32 f64 char str string bytes
byte_buf option unit seq tuple map enum identifier ignored_any
}
}
let mut deserializer = NameDeserializer(None);
let _ = D::deserialize(&mut deserializer);
deserializer.0.unwrap()
}
#[derive(Serialize, Deserialize)]
struct Vec2(f32, f32);
fn main() {
println!("{}", type_name::<Vec2>());
}