【发布时间】:2016-02-10 22:48:06
【问题描述】:
我发现自己在相同的范围内编写了带有参数的不同函数,如下所示:
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"]);
^~~~~~~~~~~~~~~
所以,没有运气。我该如何前进?
1https://github.com/rust-lang/rust/issues/8634
2https://stackoverflow.com/a/30424219/3957040
【问题讨论】:
-
您能否展示使用单独特征实现的
consume?有一个泛型类型的方法在参数或结果值中没有使用是非常可疑的。就像,我认为这是不可能的。 -
你的意思是像这个游戏围栏里的
noalias_consume(is.gd/e9qIKV) 吗?确实,它不起作用。
标签: generics rust associated-types