【发布时间】:2015-01-11 14:18:04
【问题描述】:
注意:我知道Rust invoke trait method on generic type parameter,不幸的是,那里描述的解决方法似乎对我不起作用,可能是因为我的特征是参数化的。
我尝试使用关联方法实现 参数化 trait:
trait Parameterized<T> {
fn static_call<'a>(t: &'a T) -> &'a T;
}
struct Foo;
impl Parameterized<u32> for Foo {
fn static_call<'a>(t: &'a u32) -> &'a u32 { t }
}
目标当然是以后使用这种方法:
struct PP<T, P: Parameterized<T>> {
p: P
}
impl<T, P> PP<T, P>
where P: Parameterized<T>
{
fn call_it<'a>(t: &'a T) -> &'a T {
P::static_call(t)
}
}
但不幸的是,事情从这里开始走下坡路。这里给出的语法是最明显的,但是相关的方法还没有实现,因此编译器会拒绝代码(带有令人费解的错误消息):
error: failed to resolve. Use of undeclared type or module `P`
P::static_call(t)
^~~~~~~~~~~~~~
好的,那我们试试上一个问题中描述的变通方法吧!
impl<T, P> PP<T, P>
where P: Parameterized<T>
{
fn call_it<'a>(t: &'a T) -> &'a T {
Parameterized::<T>::static_call(t)
}
}
导致:
error: type annotations required: cannot resolve `_ : Parameterized<T>`
Parameterized::<T>::static_call(t)
^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
这很公平,因为编译器确实无法推断出我的意思是Parameterized<T> 的特定实现@ 987654329@。让我们来看看用于关联类型的语法:
impl<T, P> PP<T, P>
where P: Parameterized<T>
{
fn call_it<'a>(t: &'a T) -> &'a T {
<P as Parameterized<T>>::static_call(t)
}
}
不,也不工作:
error: unexpected token: `<`
<P as Parameterized<T>>::static_call(t)
^
所以这不是注释的方式。
除了添加 &self 之外,我对解决方法的建议持开放态度。
【问题讨论】:
标签: rust