面试题答案
一键面试设计思路
- 定义trait:首先定义一个基础的trait,它包含要操作集合元素的通用方法。
- 类型约束:在trait定义中,通过关联类型或泛型参数来指定元素类型的约束,使得trait可以适用于不同类型的元素,但又满足一定规则。
- 扩展方法:利用Rust的trait扩展功能,为已定义的trait添加新的方法。这些方法应该能够处理不同类型的集合,通过泛型参数来实现对不同集合类型(如
Vec
、HashMap
等)的支持。
关键代码实现
以下以Rust为例:
// 定义基础trait
trait CollectionOperation<T> {
fn perform_operation(&self) -> Vec<T>;
}
// 为Vec<T>实现基础trait
impl<T> CollectionOperation<T> for Vec<T>
where
T: Copy,
{
fn perform_operation(&self) -> Vec<T> {
self.iter().cloned().collect()
}
}
// 为HashMap<K, V>实现基础trait,这里仅以V作为操作对象,假设只关心值
use std::collections::HashMap;
impl<K, V> CollectionOperation<V> for HashMap<K, V>
where
V: Copy,
{
fn perform_operation(&self) -> Vec<V> {
self.values().cloned().collect()
}
}
// 扩展trait,添加新功能
trait CollectionOperationExt<T>: CollectionOperation<T> {
fn new_operation(&self) -> usize {
self.perform_operation().len()
}
}
// 为实现了CollectionOperation的类型自动实现CollectionOperationExt
impl<T, C> CollectionOperationExt<T> for C
where
C: CollectionOperation<T>,
{
// 新功能的默认实现已经在trait定义中给出
}
fn main() {
let vec: Vec<i32> = vec![1, 2, 3];
let result1 = vec.new_operation();
println!("Vec new operation result: {}", result1);
let mut map = HashMap::new();
map.insert(1, "a");
map.insert(2, "b");
let result2 = map.new_operation();
println!("HashMap new operation result: {}", result2);
}
在上述代码中:
- 定义了
CollectionOperation
trait,它有一个perform_operation
方法,用于对集合元素进行操作并返回操作后的Vec
。 - 分别为
Vec<T>
和HashMap<K, V>
实现了CollectionOperation
trait,针对不同集合类型进行了相应处理。 - 定义了
CollectionOperationExt
trait 对CollectionOperation
进行扩展,添加了new_operation
方法,计算perform_operation
返回结果的长度。 - 通过
impl<T, C> CollectionOperationExt<T> for C where C: CollectionOperation<T>
为所有实现了CollectionOperation
的类型自动实现CollectionOperationExt
。 - 在
main
函数中展示了如何在Vec
和HashMap
上使用新添加的扩展方法。