[英]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.