#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 上編輯此頁 最後更新: