Hacker News new | ask | show | jobs
by choudanu4 2429 days ago
Does the PhantomData type in Rust do what you want? Or are you talking about something slightly different?

https://doc.rust-lang.org/nomicon/phantom-data.html

https://doc.rust-lang.org/std/marker/struct.PhantomData.html

So

  struct Sender<S> {
    /// Actual implementation of network I/O.
    inner: SenderImpl;  
    /// 0-sized field, doesn't exist at runtime.
    state: S;
  }
I believe could become

  struct Sender<S> {
    /// Actual implementation of network I/O.
    inner: SenderImpl;  
    /// 0-sized field, doesn't exist at runtime.
    _marker: PhantomData<S>;
  }
I've never used this PhantomData personally, so this might be wrong. Cheers!
1 comments

It does! But you still have to actually "use" it, meaning that it appears as a field in the definition, and you have pass a PhantomData value whenever you create new instances of your data type.

In Haskell, you can omit these fields entirely, and achieve the same thing just by annotating the function.

For example, in Haskell, we can have

  data Const a b = Const a
whereas in Rust, it would be:

  struct Const<A, B> {
      konst: A, 
      // does not exist at run-time
      discard: PhantomData<B>
  }
The reason for this requirement is lifetime subtyping: https://doc.rust-lang.org/nomicon/subtyping.html

Type parameter variance is inferred from usage (e.g. covariant for normal fields, contravariant for function arguments) and without a usage there's no way to infer it.