How to parse a type with invariants with serde
โ Rust ๐ 2025-09-23 ๐ค surdeus ๐๏ธ 8Following the concept of Parse, donโt validate I am wondering how to actually do this in practice with serde.
For example lets say we have the following struct:
pub struct OrderedPair<T: Ord>(T, T);
impl<T: Ord> OrderedPair<T> {
pub fn new(left: T, right: T) -> Option<Self> {
if left > right {
None
} else {
Some(Self(left, right))
}
}
}
So far so good we have a type with some invariant that gets checked when instantiating it. But now I want to make this type deserializable. If I know just derive(Deserialize) then the check of new won't be used and I could deserialize an invalid state, so basically the invariant is not guaranteed anymore.
Of course I can implement Deserialize myself but that seems a bit tedious for such a simple and very regular task as validating some invariant. Is there any better option than implementing Deserialize myself? Just note that this is a simple example in practice the structs might be bigger and the invariants more complicated.
3 posts - 2 participants
๐ท๏ธ Rust_feed