Deserialize some fields after/inside object construction?

How can I create an object and then load its state from a file? Serializable state consists of some (but not all) fields, so I want to just overwrite their values on deserialization.

Objects can be nested (creating/deleting parent object calls constructor/destructor for its field objects), and each of them has its own serializable state. Moreover, they may have cross-refetrenced (shared) fields (although only one object owns each shared field).

So, I want to have a simple de/serialization code for such constructs. I don't want to write de/serialization methods by hand, since there just too many such object types.

Can I use serde with an already created object as a deserialization target, or should I always deserialize whole objects?

Serde deserializers are pretty difficult to write when the input data isn't neatly self-contained and close to 1:1 representation of Rust struct.

I suggest deserializing to a struct that closely resembles the "shape" of the input data as-is (just deals with parsing, but not interpretation of the meaning of the data), and then convert these structs by moving data to other, higher-level structs.

1 Like

Then maybe it s possible to write a custom macro for a list of fields that should be loaded on some method for already created object, and make it working recursively for nested structs?

Something similar to this msgpack c++ example:

#include <msgpack.hpp>

struct your_class {
    int a;
    std::string b;

How complicated is to write such a macro?

It shall depend on your experience with macros, but if you are not too strict about the call-site ergonomics of the macro (i.e., you are not picky about how the macro annotations and the rest will look like), it can be easier than it looks. Maybe open a new thread with "help" and "macro" among the thread title, and explaining what you wish to achieve.

That being said, I don't think you have reached that point yet: macros are there to automate code generation, but a classic mistake is to try to come up with the macro and the generated code at the same time:

  1. let's first see some examples with manually hand-written code (feel free to use ... ellipsis for the "obvious" parts),

  2. and only then should you try to write the macro on your own and/or ask for help about it here :slightly_smiling_face:

Bonus point if you try not to focus too hard on a macro-based solution, since then it is more likely somebody comes up with a simpler solution to your problem through XY :wink:

1 Like

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.