Rust 1.18 / serde 1.0.0 有一个完整的例子:
impl<'de> Deserialize<'de> for EventKind {
fn deserialize<D>(deserializer: D) -> result::Result<EventKind, D::Error>
where D: Deserializer<'de>
{
struct FieldVisitor {
min: usize,
};
impl<'de> Visitor<'de> for FieldVisitor {
type Value = EventKind;
fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
write!(formatter, "a string containing at least {} bytes", self.min)
}
fn visit_str<E>(self, value: &str) -> result::Result<EventKind, E>
where E: serde::de::Error
{
let kind = match value {
"request" => EventKind::Request,
"ready" => EventKind::Ready,
"next" => EventKind::Next,
"reject" => EventKind::Reject,
"fail" => EventKind::Fail,
"done" => EventKind::Done,
"cancel" => EventKind::Cancel,
"suspended" => EventKind::Suspended,
s => {
return Err(serde::de::Error::invalid_value(serde::de::Unexpected::Str(s),
&self));
}
};
Ok(kind)
}
}
deserializer.deserialize_str(FieldVisitor { min: 4 })
}
}
enum EventKind {
Request,
Ready,
Next,
Reject,
Fail,
Done,
Cancel,
Suspended,
}
impl Serialize for EventKind {
fn serialize<S>(&self, serializer: S) -> result::Result<S::Ok, S::Error>
where S: Serializer
{
let kind = match *self {
EventKind::Request => "request",
EventKind::Ready => "ready",
EventKind::Next => "next",
EventKind::Reject => "reject",
EventKind::Fail => "fail",
EventKind::Done => "done",
EventKind::Cancel => "cancel",
EventKind::Suspended => "suspended",
};
serializer.serialize_str(kind)
}
}
你可以在这里看到一个类似的例子。