简体   繁体   English

在模板中具有关联类型的特征

[英]Traits with associated type in templates

I have been having problems compiling my Rust code, I managed to boil down the issue to this snippet: 我在编译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());
}

I am pretty sure I am just missing something, is there anything I need to do to make this trait work? 我很确定我只是遗漏了一些东西,有什么我需要做的才能使这个特性发挥作用吗? I am using the latest nightly alpha build (at the time of writing): 我正在使用最新的每晚alpha版本(在撰写本文时):

rustc 1.0.0-nightly (458a6a2f6 2015-01-25 21:20:37 +0000)

Unfortunately, you need to write this: 不幸的是,你需要写这个:

fn get_int<'a, T: Foo<'a, Bar=I>, I: Iterator<Item=&'a usize>>(t: T) -> usize {
  t.make()
}

That is, you have to specify explicitly that the type of Bar is an iterator of the corresponding type. 也就是说,您必须明确指定Bar的类型是相应类型的迭代器。 The trait bound inside the trait definition alone is insufficient. 单独在特质定义内的特征是不够的。

This is very much like regular type parameters work. 这非常类似于常规类型参数的工作。 Even if you write something like 即使你写了类似的东西

trait Parameterized<T: Clone> { ... }

You still need to write 你还需要写

fn do_something<P: Parameterized<T>, T: Clone>() { ... }

Or with structs: 或结构:

struct S<T: Iterator<i32>> { ... }

impl<T: Iterator<i32>> for S<T> { ... }

This does look counterintuitive (and I've stumbled upon this several times as well) and probably deserves an issue in RFC repo. 这确实看起来违反直觉(我偶然发现了几次)并且可能在RFC repo中存在问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM