Rust struct which has both a field and a reference to that same field

I have the following code and I'd like to make it work somehow.

The only requirements are that the structs A and B should be able to be derived from Serialize and Deserialize (serde). So I can't wrap the fields in something that doesn't implement Serialize or Deserialize.

You can't make self-referential types in safe Rust. The borrow checking model doesn't allow it. What is the actual, high-level problem you're trying to solve? Usually, there's almost always a better solution than self-referential types.

#[derive(Clone, Serialize, Deserialize)]
pub enum MathExpressionValue {
    Variable(String),
    Factor(Vec<Box<MathExpression>>)
}

#[derive(Clone, Serialize, Deserialize)]
pub struct MathExpression {
    value: MathExpressionValue,
    id: usize
}

pub struct MathExpressionManager<'a> {
    current_id: usize,
    all_expressions: HashMap<usize, &'a MathExpression>,
    root: MathExpression
}

As I said, I have no problems with wrapping stuff inside other types as long as :

  • MathExpressionManager can be shared between threads safely
  • MathExpression can be derived from Serialize and Deserialize

all_expressions should contain a way to get back to root

I managed to achieve that using the Arc<RwLock<>> AND adding the "rc" feature to serde.