【问题标题】:Working around the lack of associated method on parametric traits?解决参数特征缺乏相关方法的问题?
【发布时间】: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&lt;T&gt; 的特定实现@ 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)
              ^

所以这不是注释的方式。

除了添加 &amp;self 之外,我对解决方法的建议持开放态度。

【问题讨论】:

标签: rust


【解决方案1】:

在您的第一个链接中给出的使用虚拟参数指定Self 的解决方法似乎有效;调整到:

fn static_call<'a>(t: &'a T, _unused: Option<Self>) -> &'a T;

// ...

    Parameterized::static_call(t, None::<P>)

为我编译罚款。

(顺便说一句,这看起来像是关联类型 trait Parameterized { type T; 可能有用的情况,但它不能解决此问题,并且可能与您的真实非简化代码完全不同。)

【讨论】:

  • 啊,我错过了部分解决方案;好吧,让我们投票关闭这个然后:x
猜你喜欢
  • 2017-07-18
  • 2012-11-15
  • 1970-01-01
  • 2014-10-08
  • 2018-03-10
  • 2020-02-17
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多