这个错误通常会在尝试将 trait 对象化时出现。在 Rust 中,trait 对象必须是对象安全的,意味着 trait 中不能包含与 Self
相关的方法或类型。fn merge(&self, other: &Self) -> Self
这个方法使用了 Self
类型,因此无法使该 trait 对象安全。
有多种方法可以解决这个问题,其中一种是使用泛型参数来替换 Self
。例如,将 trait 定义为:
trait Mergeable {
fn merge(&self, other: &T) -> T;
}
然后在实现中将 T
替换为具体的类型,例如:
struct MyStruct {
value: i32,
}
impl Mergeable for MyStruct {
fn merge(&self, other: &MyStruct) -> MyStruct {
MyStruct {
value: self.value + other.value,
}
}
}
然后就可以使用泛型参数来创建对象安全的 trait 了。