Search code examples
rustmetaprogramming

How do I iterate through the types that implement a trait


I am dealing with currencies.

I want to be able to parse them from ticker symbols like "USD".

I have implemented a currency trait which I want to have a compile time ticker symbol.

I want to iterate through all the types that implement Currency to check if their ticker symbol is equal to the string being parsed. If so, I want to return a type of that currency.

I have this so far:

pub trait Currency {
    const TICKER_SYMBOL: String;
}

#[derive(debug)]
struct USD;
impl Currency for USD { const TICKER_SYMBOL:  String = "USD".to_string();}

impl FromStr for dyn Currency {
    type Err = &'static str;
    fn from_str(s: &str) -> Result<Self, Self::Err> {
        todo!()
    }
}

Solution

  • The strum crate + enums gave me what I wanted.

    use std::str::FromStr;
    use strum_macros::EnumString;
    
    #[derive(Debug, PartialEq, EnumString)]
    enum Currency {
        USD,
        BTC
    }
    
    #[test]
    fn parses_currencies() {
        let c = Currency::from_str("USD");
        assert_eq!(Ok(Currency::USD), c);
        let err = Currency::from_str("monopoly money");
        assert!(err.is_err());
    }