フォーマッタの共通インターフェイスを作成したいと思います。これは入力を受け取り、目的に応じてフォーマットします。空の構造体の実装を返すファクトリクラスを作成する
現在、私はFormatter実装を含むBoxを返しています(結果にラップされています)。しかし、私はこれが最良の方法だとは思わない。 Formatterの実装は空の構造体なので、Boxのヒープメモリの割り当ては意味をなさない。
pub trait Formatter {
fn format_information(&self, information: Result<Information, Error>) -> Result<String, Error>;
fn format_information_collection(&self, information: InformationCollection) -> Result<String, Error>;
}
pub struct JsonFormatter;
impl Formatter for JsonFormatter {...}
pub struct XmlFormatter;
impl Formatter for XmlFormatter {...}
// Factory to create a formatter
pub struct Factory;
impl Factory {
pub fn get_formatter(format: &str) -> Result<Box<Formatter>, Error> {
match format {
"json" => Ok(Box::new(JsonFormatter {})),
"xml" => Ok(Box::new(XmlFormatter {})),
_ => Err(Error::new(format!("No formatter found for format {}", format)))
}
}
}
// Use the factory
let formatter_box = Factory::get_formatter(format).unwrap();
let formatter = &*formatter_box as &Formatter;
錆でこれを行う正しい方法は何ですか?
ありがとうございました。私は多くのことを学びました。私はRustから始まり、私の就業日の言語はPHPです:) – cundd