rust-unofficial / patterns

A catalogue of Rust design patterns, anti-patterns and idioms
https://rust-unofficial.github.io/patterns/
Mozilla Public License 2.0
8.02k stars 366 forks source link

PhantomData and ZSTs as an anti-pattern #20

Open sgrif opened 8 years ago

sgrif commented 8 years ago

I'm a little wiped to write a full PR, and wanted to see if people agree here or not. We make extensive use of ZSTs in Diesel, which has sometimes led to the use of PhantomData, even if the type we're wrapping with it is also zero sized.

As time has gone on though, I've realized that any use of PhantomData is ultimately a sign that how you're going about implementing your hierarchy might be impossible to make object safe, which is a good thing to retain when you can. It's hard enough changing all of the fn foo<T: Foo>(foo: T) to fn foo(foo: &Foo), adding additional work on yourself is painful.

As such, I've ultimately come to the conclusion that PhantomData is a smell (maybe not an anti-pattern, but there's generally little value in distinguishing between the two)

llogiq commented 7 years ago

There is one valid use of PhantomData though, when you need to convey that your object has an instance of a type, but don't have the actual owned instance (because you keep it somewhere else, e.g. in a central store).

nrc commented 7 years ago

I think maybe the anti-pattern is something more specific about PhatomData and ZSTs, rather than any use of PhantomData. In particular, using PhantomData to support phantom types is exactly what it is intended for and should probably be covered as an idiom.