- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我需要一个返回类型名称的函数,我有这个函数可以使用 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>());
}
最佳答案
这是一个 Serializer
,它挑选出任何结构/单元结构/新类型结构/元组结构的名称。
extern crate serde;
#[macro_use]
extern crate serde_derive;
use serde::ser::{self, Serialize, Serializer, SerializeStruct, SerializeTupleStruct, Impossible};
use std::fmt::{self, Display};
fn type_name<T: Serialize>(t: &T) -> &'static str {
#[derive(Debug)]
struct NotStruct;
type Result<T> = std::result::Result<T, NotStruct>;
impl std::error::Error for NotStruct {
fn description(&self) -> &str { "not struct" }
}
impl Display for NotStruct {
fn fmt(&self, _f: &mut fmt::Formatter) -> fmt::Result { unimplemented!() }
}
impl ser::Error for NotStruct {
fn custom<T: Display>(_msg: T) -> Self { NotStruct }
}
struct TypeName;
impl Serializer for TypeName {
type Ok = &'static str;
type Error = NotStruct;
type SerializeSeq = Impossible<Self::Ok, Self::Error>;
type SerializeTuple = Impossible<Self::Ok, Self::Error>;
type SerializeTupleStruct = Struct;
type SerializeTupleVariant = Impossible<Self::Ok, Self::Error>;
type SerializeMap = Impossible<Self::Ok, Self::Error>;
type SerializeStruct = Struct;
type SerializeStructVariant = Impossible<Self::Ok, Self::Error>;
fn serialize_bool(self, _v: bool) -> Result<Self::Ok> { Err(NotStruct) }
fn serialize_i8(self, _v: i8) -> Result<Self::Ok> { Err(NotStruct) }
fn serialize_i16(self, _v: i16) -> Result<Self::Ok> { Err(NotStruct) }
fn serialize_i32(self, _v: i32) -> Result<Self::Ok> { Err(NotStruct) }
fn serialize_i64(self, _v: i64) -> Result<Self::Ok> { Err(NotStruct) }
fn serialize_u8(self, _v: u8) -> Result<Self::Ok> { Err(NotStruct) }
fn serialize_u16(self, _v: u16) -> Result<Self::Ok> { Err(NotStruct) }
fn serialize_u32(self, _v: u32) -> Result<Self::Ok> { Err(NotStruct) }
fn serialize_u64(self, _v: u64) -> Result<Self::Ok> { Err(NotStruct) }
fn serialize_f32(self, _v: f32) -> Result<Self::Ok> { Err(NotStruct) }
fn serialize_f64(self, _v: f64) -> Result<Self::Ok> { Err(NotStruct) }
fn serialize_char(self, _v: char) -> Result<Self::Ok> { Err(NotStruct) }
fn serialize_str(self, _v: &str) -> Result<Self::Ok> { Err(NotStruct) }
fn serialize_bytes(self, _v: &[u8]) -> Result<Self::Ok> { Err(NotStruct) }
fn serialize_none(self) -> Result<Self::Ok> { Err(NotStruct) }
fn serialize_some<T: ?Sized + Serialize>(self, _value: &T) -> Result<Self::Ok> { Err(NotStruct) }
fn serialize_unit(self) -> Result<Self::Ok> { Err(NotStruct) }
fn serialize_unit_struct(self, name: &'static str) -> Result<Self::Ok> {
Ok(name)
}
fn serialize_unit_variant(self, _name: &'static str, _variant_index: u32, _variant: &'static str) -> Result<Self::Ok> { Err(NotStruct) }
fn serialize_newtype_struct<T: ?Sized + Serialize>(self, name: &'static str, _value: &T) -> Result<Self::Ok> {
Ok(name)
}
fn serialize_newtype_variant<T: ?Sized + Serialize>(self, _name: &'static str, _variant_index: u32, _variant: &'static str, _value: &T) -> Result<Self::Ok> { Err(NotStruct) }
fn serialize_seq(self, _len: Option<usize>) -> Result<Self::SerializeSeq> { Err(NotStruct) }
fn serialize_tuple(self, _len: usize) -> Result<Self::SerializeTuple> { Err(NotStruct) }
fn serialize_tuple_struct(self, name: &'static str, _len: usize) -> Result<Self::SerializeTupleStruct> {
Ok(Struct(name))
}
fn serialize_tuple_variant(self, _name: &'static str, _variant_index: u32, _variant: &'static str, _len: usize) -> Result<Self::SerializeTupleVariant> { Err(NotStruct) }
fn serialize_map(self, _len: Option<usize>) -> Result<Self::SerializeMap> { Err(NotStruct) }
fn serialize_struct(self, name: &'static str, _len: usize) -> Result<Self::SerializeStruct> {
Ok(Struct(name))
}
fn serialize_struct_variant(self, _name: &'static str, _variant_index: u32, _variant: &'static str, _len: usize) -> Result<Self::SerializeStructVariant> { Err(NotStruct) }
}
struct Struct(&'static str);
impl SerializeStruct for Struct {
type Ok = &'static str;
type Error = NotStruct;
fn serialize_field<T: ?Sized + Serialize>(&mut self, _key: &'static str, _value: &T) -> Result<()> { Ok(()) }
fn end(self) -> Result<Self::Ok> {
Ok(self.0)
}
}
impl SerializeTupleStruct for Struct {
type Ok = &'static str;
type Error = NotStruct;
fn serialize_field<T: ?Sized + Serialize>(&mut self, _value: &T) -> Result<()> { Ok(()) }
fn end(self) -> Result<Self::Ok> {
Ok(self.0)
}
}
t.serialize(TypeName).unwrap()
}
#[derive(Serialize)]
struct Vec2(f32, f32);
fn main() {
println!("{}", type_name(&Vec2(0.0, 0.0)));
}
关于rust - 当类型仅为 Serialize 时,使用 serde 将类型的名称作为 String 获取,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46612327/
我有一个使用the #[serde(default)] container attribute的结构。 但是,应该有一个字段是必需的(如果输入数据中不存在该字段,则反序列化器应该出错,而不是退回到默认
我正在尝试使用 actix-web 服务器作为通往小型堆栈的网关,以保证堆栈内部的数据格式严格,同时为用户提供一些自由。 为此,我想将 JSON 字符串反序列化为结构,然后对其进行验证、再次序列化并将
正在使用 apache-hive-0.13.1。在创建表配置单元时抛出如下错误 FAILED: Execution Error, return code 1 from org.apache.hadoo
我想添加一个简单的版本方案 + 检查我的结构: #[derive(Serialize, Deserialize)] struct Versioned { version: u32, o
我正在尝试使用 Serde 加载一个 Toml 文件,它包含多个 bool 值,如果在文本文件中找不到,我想将它们全部默认为 false。 我目前的实现是: #[derive(serde::Deser
如何使用 Serde 为远程类型创建序列化程序代理对象?这是一个最小的例子(playground): use serde; // 1.0.104 use serde_json; // 1.0.48 s
我有一个枚举: #[derive(Serialize, Deserialize)] enum Action { Join, Leave, } 和一个结构: #[derive(Seria
我有一个枚举: #[derive(Serialize, Deserialize)] enum Action { Join, Leave, } 和一个结构: #[derive(Seria
在 Rust 中,我从 websocket 接收数据。为简单起见,它看起来像这样: [1, {"a": ["1.2345", 5, "9.8765"]}] 我从 websocket 获得的字符串确实
我的程序解析足够大的 json 文档(30MB),在 CPU 较慢的机器上需要 70 毫秒,我想加快这个过程,我发现 27% 的解析发生在我的 foo_document_type_deserializ
我正在尝试在配置单元中创建一个正则表达式 serde 来读取一些日志文件,但是在让它工作时遇到了问题... 日志文件看起来像这样...... 14.196.202.16:9123 11329 2
我正在使用映射列的 JSON-Serde 功能来重命名我的 json 文档中的列 'Customer ID' -> 'customer_id。我使用映射函数的原因是因为 HQL 不允许在 CREATE
我有一个包含 Text 键和 DoubleWritable 值的序列文件。当我将文件加载为外部表时 Create external table t (id String, data Double) S
假设我有这个结构: use serde::{Serialize, Deserialize}; #[derive(Deserialize)] struct MyStruct { field_1:
这段代码完全按照我的意愿序列化了一个 32 字节的数组: #[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, PartialOr
我正在使用 event_emmiter_rs用于我的应用程序中的事件处理。该库允许您订阅带有回调的事件并触发这些事件。事件采用 (strings, value) 的形式,回调采用接受值参数的闭包形式。
给定这个枚举定义: #[repr(u8)] #[derive(Debug, Serialize)] pub enum AnimalType { #[serde(rename = "cat")]
我目前正在使用 Rocket 开发一个 Web API,它使用以下结构进行错误响应: #[derive(Serialize, Deserialize)] pub struct ErrorRespons
我想解析这个日志样本 May 3 11:52:54 cdh-dn03 init: tty (/dev/tty6) main process (1208) killed by TERM signal M
我想从访问日志中提取(ip、requestUrl、timeStamp)以加载到 hive 数据库。访问日志中的一行如下。 66.249.68.6 - - [14/Jan/2012:06:25:03 -
我是一名优秀的程序员,十分优秀!