简体   繁体   English

如何在Parity Substrate自定义运行时中使用通用结构?

[英]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. 我想在Parity Substrate自定义运行时内使用Struct创建数据类型。 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 . 编译器抱怨没有找到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. 不幸的是, Sven Marnach给出的答案并不适用于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 . 它看起来像T::BalanceT::AcountId是某些特征的相关类型,因此它们只能用于表示为T实现的特性,例如MyTrait You can tell the compiler that T implements MyTrait by adding a trait bound: 您可以通过添加特征绑定告诉编译器T实现MyTrait

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.) (唯一的例外是默认情况下假定类型参数的大小 ,因此您可以在没有显式绑定的情况下进行此假设。)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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