面试题答案
一键面试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])
}
}
}