varunsrin / rusty_money

Money library for Rust
MIT License
88 stars 33 forks source link

Request: make it possible to save writing `<T: FormattableCurrency>`, and store multiple currencies in one place #69

Closed nc7s closed 11 months ago

nc7s commented 2 years ago

Current implementation requires something like this:

use {
    std::collections::HashMap,
    rusty_money::{Money, FormattableCurrency, iso, crypto},
};

#[derive(Debug)]
struct PriceList<'pl, T: FormattableCurrency> {
    pub prices: HashMap<String, Money<'pl, T>>,
}

impl<'pl, T: FormattableCurrency> PriceList<'pl, T> {
    fn new() -> Self {
        Self{ prices: HashMap::new() }
    }

    fn set_price<S: Into<String>>(&mut self, thing: S, price: Money<'pl, T>) {
        self.prices.insert(thing.into(), price);
    }

    fn get_price(&self, name: &str) -> Option<&Money<T>> {
        self.prices.get(name)
    }
}

fn main() {
    let mut pl = PriceList::new();
    pl.set_price("one", Money::from_major(1, iso::CNY));
    pl.set_price("two", Money::from_major(1, iso::USD));
    pl.set_price("coin", Money::from_str("0.01", crypto::BTC).unwrap());
    // expected struct `rusty_money::iso::Currency`, found struct `rusty_money::crypto::Currency`
    dbg!(&pl);
    dbg!(pl.get_price("one"));
}
  1. It seems somewhat cumbersome.
  2. We can't store prices of both the ISO currencies and cryptos in one list.