Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

(De)serializing any type from a (de)serializable type #110

Open
wants to merge 3 commits into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
25 changes: 25 additions & 0 deletions _src/Deserializing_any_type_from_deserializable_type.md
Original file line number Diff line number Diff line change
@@ -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<AtomicU64, D::Error> where D: Deserializer<'de> {
// Note: Option<u64> implements Deserialize, so we can just tell serde to deserialize an Option<u64> and use the result
let value = Option::<u64>::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() {}
```