繁体   English   中英

如何改变值为枚举的 StorageMap?

[英]How do I mutate a StorageMap where the value is an enum?

这是我的存储地图:

    #[pallet::getter(fn hotel_status)]
    /// Keeps track of what accounts own what Kitty.
    pub(super) type HotelStatus<T: Config> = StorageMap<
        _,
        Twox64Concat,
        T::AccountId,
        Gender,
    >;

我想使用try_mutate来改变 Gender,因为 AccountId 已经存在于 map 中,或者插入一个新条目。 这是完整的外部:

        #[pallet::weight(0)]
        pub fn activate_hotel(
            origin: OriginFor<T>,
            hotel: T::AccountId,
        ) -> DispatchResult {
            let sender = ensure_signed(origin)?;
            log::info!("signer ID: {:?}.", sender);
            let hotel_status = <HotelStatus<T>>::get(&hotel);
            ensure!(hotel_status == Some(Gender::Active), <Error<T>>::HotelAlreadyActive);
            <HotelStatus<T>>::try_mutate(hotel, |status| {
                status = Gender::Active;
            }).map_err(|_| <HotelStatus<T>>::insert(hotel, Gender::Active));
            
            Ok(())
        }

我得到的错误是

mismatched types
expected mutable reference, found enum `pallet::Gender`
note: expected mutable reference `&mut std::option::Option<pallet::Gender>`
                      found enum `pallet::Gender`rustc(E0308)
lib.rs(297, 14): expected mutable reference, found enum `pallet::Gender`

基板教程仅给出了一个示例,其中值为 vec,并且他们尝试将新元素推送到其上,因此我不知道如何改变枚举或原始类型(例如字符串、数字)。

  • Gender::Active是一个枚举
  • status&mut Option<pallet::Gender>

您不能将Gender::Active分配给status ,因为类型不同。 这就是错误消息告诉您的内容:

expected mutable reference `&mut std::option::Option<pallet::Gender>`
                      found enum `pallet::Gender`rustc(E0308)

要改变引用后面的值,您需要(在这种情况下)使用*运算符取消引用它。 *status类型是Option<pallet::Gender> 您需要将Gender::Active包装在Some变体中,然后再将其分配给*status ,因为Some(Gender::Active)类型也是Option<pallet::Gender>

try_mutate(hotel, |status| {
  *status = Some(Gender::Active);
  Ok(())
}

Ok(())是必需的,因为闭包需要返回一个Result

暂无
暂无

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

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