【问题标题】:How do I mutate a StorageMap where the value is an enum?如何改变值为枚举的 StorageMap?
【发布时间】:2021-11-22 08:54:38
【问题描述】:

这是我的 StorageMap:

    #[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 来改变性别,因为 AccountId 已经存在于地图中,或者插入一个新条目。这是完整的外部:

        #[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`

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

【问题讨论】:

    标签: rust substrate


    【解决方案1】:
    • Gender::Active 是一个枚举
    • status&amp;mut Option&lt;pallet::Gender&gt;

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

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

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

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

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

    【讨论】:

    • 对不起@Jerboas86 但您能否提供如何处理错误情况?教程中的示例似乎仅适用于 Vecs cannot infer type for type parameter 'E' declared on the associated function 'try_mutate'
    • try_mutate::&lt;_, _, (), _&gt;(hotel,... 如果您使用turbofish注释指定它是否有效?
    猜你喜欢
    • 1970-01-01
    • 2016-06-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-08-31
    • 1970-01-01
    • 2012-12-16
    相关资源
    最近更新 更多