E4005#
这个错误发生在一个特征有多个相同方法名的声明时。特征中的每个方法必须有一个唯一的名称,以避免歧义。
错误示例#
///|
trait Animal {
make_sound(Self) -> String
make_sound(Self) -> String // Error: method make_sound is declared twice
}
建议#
移除重复的方法声明,只保留每个方法名的一个定义:
///|
priv trait Animal {
make_sound(Self) -> String // Only declare the method once
}
///|
priv struct Dog {}
///|
impl Animal for Dog with make_sound(_) {
"woof"
}
///|
fn[T : Animal] describe(animal : T) -> String {
animal.make_sound()
}
///|
test {
let dog = Dog::{ }
inspect(describe(dog), content="woof")
}
如果你需要不同的方法行为,使用不同的方法名称:
///|
priv trait LoudAnimal {
make_sound(Self) -> String
make_loud_sound(Self) -> String // Use a different name for different behavior
}
///|
priv struct Cat {}
///|
impl LoudAnimal for Cat with make_sound(_) {
"meow"
}
///|
impl LoudAnimal for Cat with make_loud_sound(_) {
"MEOW"
}
///|
test {
let cat = Cat::{ }
inspect(cat.make_sound(), content="meow")
inspect(cat.make_loud_sound(), content="MEOW")
}