PhantomData<fn(U)> confuse me

here is the source code from futures/sink/with_flat_map:
        pub struct WithFlatMap<S, U, F, St>
        where
            S: Sink,
            F: FnMut(U) -> St,
            St: Stream<Item = S::SinkItem, Error=S::SinkError>,
        {
            sink: S,
            f: F,
            stream: Option<St>,
            buffer: Option<S::SinkItem>,
            _phantom: PhantomData<fn(U)>,
        }

What is the purpose of PhantomData <fn(U)> here?

If you remove the PhantomData you get an error like this.

error[E0392]: parameter `U` is never used
  --> src/lib.rs:13:27
   |
13 | pub struct WithFlatMap<S, U, F, St>
   |                           ^ unused parameter
   |
   = help: consider removing `U` or using a marker such as `std::marker::PhantomData`

It's written PhantomData<fn(U)> and not PhantomData<U> because it does not own a U just a function that takes U as an argument (f).

3 Likes

It also affects variance:
https://doc.rust-lang.org/nomicon/subtyping.html
https://doc.rust-lang.org/nomicon/phantom-data.html#table-of-phantomdata-patterns

3 Likes
3 Likes

Regarding the phantomdata pattern table behind the 2nd link, I assume that "variant" is an abbreviation for "covariant"?

I believe so, yes.

2 Likes