[英]Traits with associated type in templates
我在編譯Rust代碼時遇到了問題,我設法將問題歸結為這個代碼片段:
use std::slice::Iter;
pub trait Foo<'a> {
type Bar: Iterator<Item=&'a usize>;
fn make(&self) -> usize;
}
pub struct Juice;
impl <'a> Foo<'a> for Juice {
type Bar = Iter<'a, usize>;
fn make(&self) -> usize { 0us }
}
// Uncomment this line to break things
// fn get_int<'a, T: Foo<'a>>(t: T) -> usize {
// t.make()
// }
fn main() {
println!("Hello, {:?} world!" , Juice.make());
}
我很確定我只是遺漏了一些東西,有什么我需要做的才能使這個特性發揮作用嗎? 我正在使用最新的每晚alpha版本(在撰寫本文時):
rustc 1.0.0-nightly (458a6a2f6 2015-01-25 21:20:37 +0000)
不幸的是,你需要寫這個:
fn get_int<'a, T: Foo<'a, Bar=I>, I: Iterator<Item=&'a usize>>(t: T) -> usize {
t.make()
}
也就是說,您必須明確指定Bar
的類型是相應類型的迭代器。 單獨在特質定義內的特征是不夠的。
這非常類似於常規類型參數的工作。 即使你寫了類似的東西
trait Parameterized<T: Clone> { ... }
你還需要寫
fn do_something<P: Parameterized<T>, T: Clone>() { ... }
或結構:
struct S<T: Iterator<i32>> { ... }
impl<T: Iterator<i32>> for S<T> { ... }
這確實看起來違反直覺(我偶然發現了幾次)並且可能在RFC repo中存在問題。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.