[英]How to use generic structs in the Parity Substrate custom runtime?
我想在Parity Substrate自定义运行时内使用Struct
创建数据类型。 数据类型是通用的,因此我可以在不同类型上使用它。
我正在尝试以下,但它没有编译。 编译器抱怨没有找到T
子类型。
pub struct CustomDataType<T> {
data: Vec<u8>,
balance: T::Balance,
owner: T::AccountId,
}
我应该能够编译一个通用的结构。
不幸的是, Sven Marnach给出的答案并不适用于Parity Substrate。 在结构顶部使用了额外的派生宏,这些宏在沿着“直观”路径时会引起问题。
在这种情况下,您应该将所需的特征直接传递到自定义类型,并为结构的上下文创建新的泛型。
像这样的东西:
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>;
}
}
它看起来像T::Balance
和T::AcountId
是某些特征的相关类型,因此它们只能用于表示为T
实现的特性,例如MyTrait
。 您可以通过添加特征绑定告诉编译器T
实现MyTrait
:
pub struct CustomDataType<T: MyTrait> {
data: Vec<u8>,
balance: T::Balance,
owner: T::AccountId,
}
通常,如果类型受适当的类型边界限制,则只能假定泛型类型的属性,方法和关联类型。 (唯一的例外是默认情况下假定类型参数的大小 ,因此您可以在没有显式绑定的情况下进行此假设。)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.