我想爲格式化程序創建一個通用接口,它將根據其用途來接受輸入並進行格式化。創建一個返回空結構實現的工廠類
目前我正在返回包含格式化程序實現(包裝到結果中)的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中做到這一點的正確方法?
謝謝你的回答。我學到了很多。我從Rust開始,我的工作日語言是PHP :) – cundd