varunsrin / rusty_money

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

fix: forward lifetime annotation to ExchangeRate in set_rate #75

Closed affanshahid closed 1 year ago

affanshahid commented 2 years ago

Fixed an issue with the Exchange::set_rate function which specified that the passed in reference for the ExchangeRate needs to have the same lifetime ('a) as the Exchange instance. This is incorrect as the instance needs to have the same lifetime as the currencies stored inside its ExchangeRate map values (and not just this particular instance of ExchangeRate that was passed in). The change simply forwards the lifetime annotation to ExchangeRate.

This allows functions to create and return Exchanges that just use the static currencies like so:

fn get_exchange() -> Exchange<'static, Currency> {
    let mut exchange: Exchange<'static, Currency> = Exchange::new();
    let rate: ExchangeRate<'static, Currency> =
        ExchangeRate::new(iso::USD, iso::PKR, dec!(237)).unwrap();
    exchange.set_rate(&rate); // this line would previously not compile with "`rate` does not live long enough"
    exchange
}