面试题答案
一键面试// 定义自定义特征DataProcessor
trait DataProcessor {
type Input;
type Intermediate;
type Output;
fn process_step1(&self, input: Self::Input) -> Result<Self::Intermediate, String>;
fn process_step2(&self, intermediate: Self::Intermediate) -> Result<Self::Output, String>;
}
// 定义结构体代表不同的数据处理流程
struct Processor1;
impl DataProcessor for Processor1 {
type Input = i32;
type Intermediate = i32;
type Output = i32;
fn process_step1(&self, input: Self::Input) -> Result<Self::Intermediate, String> {
Ok(input * 2)
}
fn process_step2(&self, intermediate: Self::Intermediate) -> Result<Self::Output, String> {
Ok(intermediate + 1)
}
}
struct Processor2;
impl DataProcessor for Processor2 {
type Input = String;
type Intermediate = usize;
type Output = bool;
fn process_step1(&self, input: Self::Input) -> Result<Self::Intermediate, String> {
Ok(input.len())
}
fn process_step2(&self, intermediate: Self::Intermediate) -> Result<Self::Output, String> {
Ok(intermediate > 5)
}
}
// 编写处理函数
fn process_all(processors: &[&dyn DataProcessor]) {
for processor in processors {
match processor.process_step1(match processor {
&Processor1 => 5_i32,
&Processor2 => "hello world".to_string(),
_ => return,
}) {
Ok(intermediate) => match processor.process_step2(intermediate) {
Ok(output) => println!("Output: {:?}", output),
Err(e) => println!("Error in step2: {}", e),
},
Err(e) => println!("Error in step1: {}", e),
}
}
}
你可以使用以下方式调用这个函数:
fn main() {
let processor1 = Processor1;
let processor2 = Processor2;
let processors = &[&processor1 as &dyn DataProcessor, &processor2 as &dyn DataProcessor];
process_all(processors);
}