E4038#
该类型的特征对象是不允许的。
错误示例:#
fn main {
let a = 3 as &Eq
}
在上述例子中,试图创建一个 Eq
特征的对象。这是不允许的,因为这个特征不是对象安全的。
Eq
特征定义如下:
pub(open) trait Eq {
op_equal(Self, Self) -> Bool
}
因此在第 2 行报错:
Trait object for Eq is not allowed: `Self` occur multiple times in the type of method op_equal
建议#
使用一个对象安全的特征来创建一个特征对象。
一个特征要是类型安全的,它的可调用函数必须使用并且只能使用 Self
类型作为第一个参数。例如,Show
就是这样一个特征:
pub(open) trait Show {
output(Self, &Logger) -> Unit
to_string(Self) -> String
}