// 定义自定义trait
trait Processable {
fn process(&self) -> Self;
}
// 泛型函数实现
fn process_container<T: Processable + Clone + std::fmt::Debug>(input: &Vec<T>) -> Vec<T> {
input.iter()
.map(|element| element.process())
.collect()
}
// 示例结构体并实现相关trait
struct ExampleStruct {
value: i32,
}
impl Processable for ExampleStruct {
fn process(&self) -> Self {
ExampleStruct { value: self.value * 2 }
}
}
impl Clone for ExampleStruct {
fn clone(&self) -> Self {
ExampleStruct { value: self.value }
}
}
impl std::fmt::Debug for ExampleStruct {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "ExampleStruct {{ value: {} }}", self.value)
}
}
fn main() {
let input_vec: Vec<ExampleStruct> = vec![ExampleStruct { value: 1 }, ExampleStruct { value: 2 }];
let result = process_container(&input_vec);
println!("{:?}", result);
}