docs

#E0072: impl 缺少 trait 项

trait 的 impl 必须定义 trait 中声明且没有默认值的每个方法、关联类型和关联常量。添加缺少的项(type Item = i32;)。

nabi
trait Shape {
    fn area(self) -> f64;
    fn name(self) -> str;
}
struct Sq { s: f64; }
impl Shape for Sq {
    fn area(self) -> f64 { self.s * self.s }
}
error[E0072]: impl of trait `Shape` for `Sq` is missing method `name`
  --> main.nabi:6:1
   |
 6 | impl Shape for Sq {
   | ^^^^

添加缺少的方法:

nabi
trait Shape {
    fn area(self) -> f64;
    fn name(self) -> str;
}
struct Sq { s: f64; }
impl Shape for Sq {
    fn area(self) -> f64 { self.s * self.s }
    fn name(self) -> str { "square" }
}
println(Sq { s: 1.0 }.name());
square

trait 中声明且没有默认值的关联类型也必须给出;help 会指出 impl 的方法为它使用的类型:

nabi
struct Count { n: i32; }
impl Iterator for Count {
    fn next(ref self) -> i32 | none {
        if self.n > 2 { return none; }
        self.n += 1;
        self.n
    }
}
error[E0072]: impl of `Iterator` for `Count` is missing associated type `Item`
  --> main.nabi:2:1
   |
 2 | impl Iterator for Count {
   | ^^^^
   |
   = help: the trait declares `type Item` with no default: add `type Item = i32;` to the impl

添加关联类型:

nabi
struct Count { n: i32; }
impl Iterator for Count {
    type Item = i32;
    fn next(ref self) -> i32 | none {
        if self.n > 2 { return none; }
        self.n += 1;
        self.n
    }
}
for v in (Count { n: 0 }) { println(f"{v}"); }
1
2
3

相关错误码:E0073 impl 项不在 trait 中,E0074 impl 项与 trait 不一致

发现错误? 在 GitHub 上编辑此页 最后更新: