rustsubstrate

calculate total price in rust


I have list of struct for store basket of online store :

pub struct UserTransationHistory<T: Config> {
    transactionId: <T as frame_system::Config>::Hash,
    items: Vec<UserBasketItemItem<T>>,
    customerPay: bool,
    confirmPay: bool,
    storeOwner: T::AccountId,
    storeId: <T as frame_system::Config>::Hash,
}

pub struct UserBasketItemItem<T: Config> {
    itemId: <T as frame_system::Config>::Hash,
    count: u32,
    price: u32,
}

i wanna to calcualte all basket price , i wrote this code :

        Baskets::<T>::mutate(storeId, |basket| -> DispatchResult {
            match basket {
                Some(basket) => {
                    let mut total_price = 0;
                    basket.items.iter().map(|x| total_price += x.price).rev();
                    log::info!("**************** Total Price {:?}", total_price);
                    Ok(())
                },
                _ => Err(<Error<T>>::StoreItemNotFound.into()),
            }
        });

i aded items on basket with price 10 but every time i log the total_price it shows me 0 .

**whats the problem ? how can i solve this problem ? **

Baskets::<T>::mutate(storeId, |basket| -> DispatchResult {
                match basket {
                    Some(basket) => {
                        let mut total_price = 0;
                        basket.items.iter().map(|x| total_price += x.price).rev();
                        log::info!("**************** Total Price {:?}", total_price);
                        Ok(())
                    },
                    _ => Err(<Error<T>>::StoreItemNotFound.into()),
                }
            });

Solution

  • Iterators in rust are lazy. The line basket.items.iter().map(|x| total_price += x.price).rev() does nothing, because none "consuming" method was called on the iterator. If you want to add numbers together in an iterator you could use sum. So try this:

    let total_price: u32 = basket.items.iter().map(|x| *x.price).sum();