简体   繁体   中英

How to use generic structs in the Parity Substrate custom runtime?

I want to create a data type using Struct inside a Parity Substrate custom runtime. The data type is intended to be generic so that I can use it over different types.

I am trying the following, but it's not compiling. The compiler complains about sub-types not found for T .

pub struct CustomDataType<T> {
    data: Vec<u8>,
    balance: T::Balance,
    owner: T::AccountId,
}

I should be able to compile a generic struct.

Unfortunately, the answer that Sven Marnach gives does not work in the context of Parity Substrate. There are additional derive macros which are used on top of the struct which cause issues when going down the "intuitive" path.

In this case, you should pass the traits needed directly into your custom type and create new generics for the context of the struct.

Something like this:

use srml_support::{StorageMap, dispatch::Result};

pub trait Trait: balances::Trait {}

#[derive(Encode, Decode, Default)]
pub struct CustomDataType <Balance, Account> {
    data: Vec<u8>,
    balance: Balance,
    owner: Account,
}

decl_module! {
    // ... removed for brevity
}

decl_storage! {
    trait Store for Module<T: Trait> as RuntimeExampleStorage {
        Value get(value): CustomDataType<T::Balance, T::AccountId>;
    }
}

We just created a doc for this exact scenario which I hope helps.

It looks like T::Balance and T::AcountId are assoicated types of some trait, so they can be only used if that trait, say MyTrait , is implemented for T . You can tell the compiler that T implements MyTrait by adding a trait bound:

pub struct CustomDataType<T: MyTrait> {
    data: Vec<u8>,
    balance: T::Balance,
    owner: T::AccountId,
}

In general, you can only assume properties, methods and asscociated types of a generic type if the type is restricted by appropriate type bounds. (The only exception is that type parameters are assumed to be sized by default, so you can make this assumption without an explicit bound.)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM