MST

星途 面试题库

面试题:Rust自定义特征的复杂关联类型与特征对象

创建一个复杂的自定义特征 `DataProcessor`,它有多个关联类型:`Input`、`Intermediate` 和 `Output`。`DataProcessor` 特征包含两个方法:`process_step1`,接受 `Input` 类型参数并返回 `Intermediate` 类型值;`process_step2`,接受 `Intermediate` 类型参数并返回 `Output` 类型值。接着定义一系列结构体,分别代表不同的数据处理流程,都实现 `DataProcessor` 特征。最后,编写一个函数,它接受一个 `DataProcessor` 特征对象的切片,对每个特征对象依次调用 `process_step1` 和 `process_step2` 方法,并处理可能出现的类型不匹配或其他错误情况。请用完整且正确的Rust代码实现上述要求。
28.8万 热度难度
编程语言Rust

知识考点

AI 面试

面试题答案

一键面试
// 定义自定义特征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);
}