rusty_money icon indicating copy to clipboard operation
rusty_money copied to clipboard

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

Open nc7s opened this issue 2 years ago • 0 comments

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.

nc7s avatar May 07 '22 09:05 nc7s