4

I see that some pallets wrap phantom data:

pub struct Pallet<T>(PhantomData<T>);

and others not:

pub struct Pallet<T>(_);

Why is it there?
Do I need this in my pallet as well?

2 Answers 2

3

The #[pallet::pallet] macro simply replaced the _ in the definition above to PhantomData<T>.

See the notes here:

https://github.com/paritytech/substrate/blob/master/frame/support/procedural/src/pallet/expand/pallet_struct.rs

/// * Add derive trait on Pallet
/// * Implement GetStorageVersion on Pallet
/// * Implement OnGenesis on Pallet
/// * Implement `fn error_metadata` on Pallet
/// * declare Module type alias for construct_runtime
--> /// * replace the first field type of `struct Pallet` with `PhantomData` if it is `_`
/// * implementation of `PalletInfoAccess` information
/// * implementation of `StorageInfoTrait` on Pallet

and the code:

// If the first field type is `_` then we replace with `PhantomData`
if let Some(field) = pallet_item.fields.iter_mut().next() {
    if field.ty == syn::parse_quote!(_) {
        field.ty = syn::parse_quote!(
            #frame_support::sp_std::marker::PhantomData<(#type_use_gen)>
        );
    }
}

So it is the same thing, and just a friendly "type inference magic" done for the pallet developer.

5

A phantom type parameter is simply a type parameter which is never used. In Rust, this often causes the compiler to complain, and the solution is to add a “dummy” use by way of PhantomData.

Adding a PhantomData field to your type tells the compiler that your type acts as though it stores a value of type T, even though it doesn’t really. This information is used when computing certain safety properties.

2
  • So basically just to make the compiler happy? No change in the pallet execution logic? Feb 24, 2022 at 17:47
  • 2
    There is a bit more about it, I think. The example in the substrate docs about lifetime is great, explaining how you can use PhantomData to define that a certain struct should not outlive 'a for that concrete example. But I am not aware if this affects the execution of this logic. I would guess it does not. Feb 24, 2022 at 18:03

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.