首页 > 解决方案 > decl_storage 中 pub 的用途是什么?

问题描述

在基板中实现运行时模块时,给定以下存储

decl_storage! {
  trait Store for Module<T: Trait> as CatAuction {
    Kitties get(kitties): map T::Hash => Kitty<T::Hash, T::Balance>;
    KittyOwner get(owner_of): map T::Hash => Option<T::AccountId>;
    OwnedKitties get(kitties_owned): map T::AccountId => T::Hash;

    pub AllKittiesCount get(all_kitties_cnt): u64;
    Nonce: u64;

    // if you want to initialize value in storage, use genesis block
  }
}

pub前面的目的是AllKittiesCount什么?因为不管有pub没有,polkadot UI 还是可以查询到的,就好像它是一个公共变量一样。

标签: substrateparity-io

解决方案


在这里稍微扩展一下,就像任何 Rust 类型一样,您需要明确不同类型的可见性。该decl_storagestruct会为您的每个存储项目生成一个。例如:

decl_storage! {
    trait Store for Module<T: Trait> as TemplateModule {
        Something get(something): u32;
    }
}

将导致(为清楚起见删除了一些内容):

struct Something<T: Trait>(...);

impl <T: Trait> ... for Something<T> {
    fn get<S: ... >(storage: &S) -> Self::Query {
        storage.get(...).unwrap_or_else(|| Default::default())
    }
    fn take<S: ...>(storage: &S) -> Self::Query {
        storage.take(...).unwrap_or_else(|| Default::default())
    }
    fn mutate<R, F: FnOnce(&mut Self::Query) -> R, S: ...>(f: F, storage: &S) -> R {
        let mut val = <Self as ...>::get(storage);
        let ret = f(&mut val);
        <Self as ...>::put(&val, storage);
        ret
    }
}

如果您制作存储项目pub,您只需pubstruct Something. 这意味着,您现在可以从其他模块调用结构公开的所有这些函数,例如get, 。否则,您将需要创建自己的公共函数来公开 API 以修改存储。takemutate


推荐阅读