2016-02-10 50 views
2

我发现自己相同的边界下与议论文写作不同的功能,例如:别名特质界定不指定具体的相关类型

pub fn foo<T>(mut self, path: T) -> Self where 
    T: IntoIterator, 
    T::Item: AsRef<str>, 
{ 
    // ... 
} 

pub fn bar<T>(mut self, path: T) -> Self where 
    T: IntoIterator, 
    T::Item: AsRef<str>, 
{ 
    // ... 
} 

感觉,这是一个有点烦琐,我试图别名这些界限。但我没有找到办法。最近我得到了,检查了几个地方后[1],[2],是这样的:

trait Path { 
    type I: IntoIterator<Item = Self::S>; 
    type S: AsRef<str>; 
} 

impl<T, U> Path for T where 
    T: IntoIterator<Item = U>, 
    U: AsRef<str>, 
{ 
    type I = T; 
    type S = U; 
} 

现在,作为一个例子,该编译罚款:

fn into_vec<T: Path>(it: T::I) -> Vec<String> { 
    it.into_iter() 
     .map::<String, _>(|x| x.as_ref().into()) 
     .collect() 
} 

但是,当我尝试使用它:

fn consume<T: Path>() { 
    into_vec::<T>(&["one", "two"]); 
} 

我得到以下错误:

src/lib.rs:104:19: 104:34 error: mismatched types: 
expected `<T as Path>::I`, 
    found `&[&str; 2]` 
(expected associated type, 
    found &-ptr) [E0308] 
src/lib.rs:104  into_vec::<T>(&["one", "two"]); 
           ^~~~~~~~~~~~~~~ 

所以,没有运气。我该如何前进?


https://github.com/rust-lang/rust/issues/8634
https://stackoverflow.com/a/30424219/3957040

+0

你可以显示'消费'实施与单独的特质? *非常可疑的是有一个泛型类型的方法,它没有在参数*或*结果值中使用。就像,我不认为这是可能的。 – Shepmaster

+0

你的意思是在这个围栏(http://is.gd/e9qIKV)中使用'noalias_consume'吗?事实上,这是行不通的。 – Pablo

回答

2

How can I go forward?

你不能直接。让我们来看看你的函数:

fn consume<T: Path>() { 
    into_vec::<T>(&["one", "two"]); 
} 

这是说“为实现Path任何类型,调用into_vec用绳子一片”。但是,您无法保证无论T是什么,它都会接受一小段字符串。

寻找另一个方向,许多类型可以接受字符串的片,所以它将使T暧昧。

从第三个方向看,类型推断无法决定什么应该是T,因为它没有用作参数或返回值。

你可以得到它通过明确说明你想要的T工作:

fn consume() { 
    into_vec::<&[&'static str]>(&["one", "two"]); 
} 

为了澄清,这有没有关系的性状组合成另一种特质。这将是任何特质的问题。

相关问题