3 ms·
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
by choudanu4 7y 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/nomicon/phantom-data.html
https://doc.rust-lang.org/std/marker/struct.PhantomData.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!
- dmkolobov 7y agoIt 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> }
- Rusky 7y agoThe reason for this requirement is lifetime subtyping: https://doc.rust-lang.org/nomicon/subtyping.html 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.