[英]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.