Why do the methods defined in the traits in serde rely on moves instead of borrows?

Why are the methods in serde::Serializer defined such that they take Self instead of &mut Self? For me the most "natural" choice would be to define the methods such that they take &mut Self for similar reasons that core::hash::Hasher has its methods defined taking &mut Self, namely that types that implement the trait are almost certainly "mutable" and one will likely want to re-use such types to hash other things.

Because of this design decision, for a type Foo, I feel like one will almost always implement serde::Serializer for &'a mut Foo (and not Foo) just like serde_json::Serializer does.

Well it's because you can only serialize one item.

2 Likes

I apologize. I clearly asked this question in haste. I assumed if you had something like

struct Foo {
    x: u32,
    y: u32,
}

and you wanted to implement serde::Serialize for Foo you'd serialize each field via serialize_u32 (similar to how one would likely hash Foo). Had I actually attempted this like I should have, I would have found this would fail due to the moves—which I should have been able to deduce from the signatures alone :(. Inserts foot in mouth.

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.