[英]How do I mutate a StorageMap where the value is an enum?
here is my 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,
>;
I want to use try_mutate
to either mutate the Gender because the AccountId already exists in the map, or insert a new entry.我想使用
try_mutate
来改变 Gender,因为 AccountId 已经存在于 map 中,或者插入一个新条目。 Here's the full extrinsic:这是完整的外部:
#[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(())
}
the error I'm getting is我得到的错误是
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`
The substrate tutorials only give an example where the value is a vec and they try to push a new element onto it so I'm at a loss how to mutate an enum or primitive type (eg string, number).基板教程仅给出了一个示例,其中值为 vec,并且他们尝试将新元素推送到其上,因此我不知道如何改变枚举或原始类型(例如字符串、数字)。
Gender::Active
is an enum Gender::Active
是一个枚举status
is &mut Option<pallet::Gender>
status
是&mut Option<pallet::Gender>
You can't assign Gender::Active
to status
, because there are not the same type.您不能将
Gender::Active
分配给status
,因为类型不同。 This is what the error message is telling you:这就是错误消息告诉您的内容:
expected mutable reference `&mut std::option::Option<pallet::Gender>`
found enum `pallet::Gender`rustc(E0308)
To mutate the value behind the reference you need (in this case) to dereference it with *
operator.要改变引用后面的值,您需要(在这种情况下)使用
*
运算符取消引用它。 *status
type is Option<pallet::Gender>
. *status
类型是Option<pallet::Gender>
。 You need to wrap Gender::Active
in Some
variant before assigning it to *status
, since Some(Gender::Active)
type is also Option<pallet::Gender>
.您需要将
Gender::Active
包装在Some
变体中,然后再将其分配给*status
,因为Some(Gender::Active)
类型也是Option<pallet::Gender>
。
try_mutate(hotel, |status| {
*status = Some(Gender::Active);
Ok(())
}
Ok(())
is required because the closure needs to return a Result
Ok(())
是必需的,因为闭包需要返回一个Result
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.