MST

星途 面试题库

面试题:Rust trait的关联类型与方法重载

定义一个`trait`叫`Container`,包含一个关联类型`Item`,以及两个方法:`add_item`用于向容器添加一个`Item`类型的元素,`get_item`用于根据索引获取`Item`类型的元素(假设索引为`usize`类型)。接着定义一个结构体`MyBox`实现`Container` trait,在实现中使用`Vec`来存储元素。注意处理`get_item`可能出现的越界情况,使用`Result`类型返回结果。
18.2万 热度难度
编程语言Rust

知识考点

AI 面试

面试题答案

一键面试
trait Container {
    type Item;
    fn add_item(&mut self, item: Self::Item);
    fn get_item(&self, index: usize) -> Result<&Self::Item, &'static str>;
}

struct MyBox<T> {
    items: Vec<T>,
}

impl<T> Container for MyBox<T> {
    type Item = T;
    fn add_item(&mut self, item: Self::Item) {
        self.items.push(item);
    }
    fn get_item(&self, index: usize) -> Result<&Self::Item, &'static str> {
        if index >= self.items.len() {
            Err("Index out of bounds")
        } else {
            Ok(&self.items[index])
        }
    }
}