![](/img/trans.png)
[英]How do I create a new vector of Trait from vectors of types that implement Trait?
[英]How do I iterate through the types that implement a trait
我正在处理货币。
我希望能够从像“USD”这样的股票代码中解析它们。
我已经实现了一个货币特征,我希望它有一个编译时代码。
我想遍历所有实现 Currency 的类型,以检查它们的股票代码是否等于正在解析的字符串。 如果是这样,我想返回一种该货币。
到目前为止我有这个:
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!()
}
}
弹奏箱+ 枚举给了我想要的东西。
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());
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.