簡體   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