1

Suppose I have a Zoo consisting of Animals, where Animals need to have a reference to their Species. (Species can't just be an owned value underneath Animal, because it contains mutable data like population numbers, etc.) There are a few ways I can represent this. Off the top of my head:

  1. Animal can hold a reference to to Species with a lifetime parameter on Animal
  2. Animal can hold an Arc<Species> to avoid putting lifetime parameters everywhere
  3. Animal can hold a SpeciesID (likely just wrapping a usize), and just keep a Map<SpeciesID, Species> elsewhere (basically implement my own reference to avoid the borrow checker altogether.)

I want to use serde to save/load the state of my Zoo. AFAIK, this is impossible except by option #3 above, as from How do I use Serde to deserialize structs with references from a reader? it sounds like I can't serialize/de-serialize references at all.

This feels like I'm making a mistake, though: I'm basically re-inventing the wheel to avoid the borrow checker, by implementing my own clunky references through SpeciesID. It also requires that the set of Species be passed as a parameter to any operation on Animal that has to access Species, which wouldn't be the case for options 1 or 2.

As an added complication, I plan to have multi threading involved in this mess eventually, so Mutexs may be a thing at some level.

I could also see having alternate forms for serialization vs. runtime, with some translation step to convert rust references to and from the SpeciesID model around serialization. That sounds like a lot of error prone boiler plate, though.

Is there a better approach to this that I'm missing?

Edward Peters
  • 3,623
  • 2
  • 16
  • 39
  • 4
    Serde can definitely serialize references, but not deduplicate them. Deserialization is more involved, though. – Chayim Friedman Jul 10 '23 at 15:04
  • 1
    Using some kind of mapping between serde representation and the reference representation is how I would implement this (if I wouldn't go the `Map` route). There are multiple ways to implement that, though. – Chayim Friedman Jul 10 '23 at 15:08
  • Question with a [similar problem](https://stackoverflow.com/questions/71619596/the-trait-bound-a-chainchaina-deserialize-is-not-satisfied/71625754) (but not a duplicate) with an answer ultimately going for the translation step approach. – Caesar Jul 10 '23 at 22:53
  • @ChayimFriedman Can you elaborate on what serializing/deserializing with references would even look like? I mean, my understanding is you can't even make a struct which contains both values and references to those values - so are you serializing references to something from outside the serialized value, or...? – Edward Peters Jul 11 '23 at 14:12

0 Answers0