varunsrin / rusty_money

Money library for Rust
MIT License
86 stars 32 forks source link

Add lifetime to get_rate return type to prevent lifetime conflicts #49

Closed JavedNissar closed 3 years ago

JavedNissar commented 3 years ago

Added an explicit lifetime to the return type of exchange.get_rate to prevent lifetime conflicts between it and other functions. To demonstrate where these lifetime conflicts come up, here's the following code:

fn convert<'a, T: FormattableCurrency>(exchange: &Exchange<'a, T>, money: &Money<'a, T>, currency: &T) -> Result<Money<'a, T>, ErrorCode> {
    let exchange_rate_pair = exchange.get_rate(money.currency(), currency);

    if let Some(exchange_rate_pair) = exchange_rate_pair {
        let cur_money = exchange_rate_pair.convert(money.clone())?;
        Ok(cur_money)
    } else{
        Err(ErrorCode::CouldNotFindExchangeRate)
    }
}

In this code, there's an error where it requests an explicit lifetime on exchange because the lifetime on the values within the result of get_rate don't match the lifetimes everywhere else ('a). This should resolve that problem.

varunsrin commented 3 years ago

thanks for the pr!