diff --git a/_src/Deserializing_any_type_from_deserializable_type.md b/_src/Deserializing_any_type_from_deserializable_type.md new file mode 100644 index 00000000..786a35d7 --- /dev/null +++ b/_src/Deserializing_any_type_from_deserializable_type.md @@ -0,0 +1,25 @@ +# (De)serializing any type from a (de)serializable type + +Sometime it's practical to (de)serialize a field of a type that does not implement (de)serialize itself from a field that does. + +Example: + +```rust +use std::sync::atomic::AtomicU64; +use serde::{Deserialize, Deserializer}; + +fn deserialize_atomic_u64<'de, D>(deserializer: D) -> Result where D: Deserializer<'de> { + // Note: Option implements Deserialize, so we can just tell serde to deserialize an Option and use the result + let value = Option::::deserialize(deserializer)?; + Ok(AtomicU64::new(value.unwrap_or_default())) +} + +# #[allow(dead_code)] +struct Foo { + // Note: the same trick works for serialize_with as well + #[serde(deserialize_with="deserialize_atomic_u64")] + atomic: AtomicU64, +} +# +# fn main() {} +```