The following code compiles only if I include the line marked with "???". If I remove the line I get lots of error message about parameter "S" never being used. I stumbled upon this "problem" in a larger scenario and had a hard time pinning it down. As far as I can tell, it happens due to the circular references between the types.
struct Question<S> {
x: Vec<AnswerRef<S>>,
_y: PhantomData<S> // ???
}
struct QuestionRef<S>(Rc<Question<S>>);
struct Answer<S> {
x: Option<QuestionRef<S>>
}
struct AnswerRef<S>(Rc<Answer<S>>);
Adding the PhantomData
solves the problem, but I don’t understand why. I don’t see why it should make a difference in this case. Can somebody explain it to me?
>Solution :
The Rust compiler is quite clever here, it detects the cyclic usage of S
and determines that you can remove it completely to get the same data structures. You can use PhantomData
to "use" type parameters that are unused otherwise as they are here.