[英]Traits with default methods that depend on a bound of an associated type
我想不出一种方法来使此代码使用--cfg on_trait
进行编译:
trait DigitCollection: Sized {
type Iter: Iterator<Item = u8>;
fn digit_iter(self) -> Self::Iter;
#[cfg(on_trait)]
fn digit_sum(self) -> u32 {
self.digit_iter()
.map(|digit: u8| digit as u32)
.fold(0, |sum, digit| sum + digit)
}
}
#[cfg(not(on_trait))]
fn digit_sum<T: DigitCollection>(collection: T) -> u32 {
collection.digit_iter()
.map(|digit: u8| digit as u32)
.fold(0, |sum, digit| sum + digit)
}
fn main() {
}
使用on_trait
此操作失败:
trait.rs:7:14: 7:26 error: type annotations required: cannot resolve `<<Self as DigitCollection>::Iter as core::iter::Iterator>::Item == u8` [E0284]
trait.rs:7 self.digit_iter()
^~~~~~~~~~~~
error: aborting due to previous error
没有on_trait
,它编译就很好。 请注意, not(on_trait)
变体的不同之处仅在于它是一个自由函数而不是默认方法。
编辑:我对此打开了一个问题: rust-lang / rust#22036
现在,此代码可根据需要进行编译:
trait DigitCollection: Sized {
type Iter: Iterator<Item = u8>;
fn digit_iter(self) -> Self::Iter;
fn digit_sum(self) -> u32 {
self.digit_iter()
.map(|digit: u8| digit as u32)
.fold(0, |sum, digit| sum + digit)
}
}
fn main() {}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.