I'm writing a small budgeting program as a side project to learn Rust. Serde handles serialization and deserialization. However, there may be a large number of transactions (accessed by UUID). I would like to cache UUID->Transaction in a HashSet while deserializing. However, I am getting a recursion error and cannot figure out why.
Transaction is the type that I would like cached:
use serde::{Serialize};
use uuid::Uuid;
#[derive(Serialize, Debug)]
pub struct Transaction {
pub(crate) id: Uuid,
...
}
Each of these is owned by an Account, which also provides the custom deserialization code:
use serde::{Serialize, Deserialize};
use uuid::Uuid;
#[derive(Serialize, Deserialize)]
pub struct Account {
pub(super) id: Uuid,
pub name: String,
pub transactions: Vec<Transaction>
}
impl<'de> Deserialize<'de> for Transaction {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where D: serde::de::Deserializer<'de> {
let trans = serde::de::Deserialize::deserialize(deserializer)?;
// Caching would go here
Ok(trans)
}
}
However, the call to Deserialize::deserialize(deserializer)? gives me the following error:
| / fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
31 | | where D: serde::de::Deserializer<'de> {
| |_____________________________________________^ cannot return without recursing
32 |
33 | let trans = serde::de::Deserialize::deserialize(deserializer)?;
| ------------------------------------------------- recursive call site
|
= help: a `loop` may express intention better if this is on purpose
= note: `#[warn(unconditional_recursion)]` on by default
I see how this could be a recursive call, and know the compiler is right, as the stack overflows at runtime. But what should I do to break the cycle? I was following the advice given in another post here or even here. I don't see how that code differs from my own (i.e., why the other code also does not have the same recursive issue).