Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Why do I have to use PhantomData? What is it doing in this case?

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading