为什么通用函数调用语法在正常函数调用时没有编译?

时间:2017-02-22 10:57:09

标签: rust

以下是展示我问题的代码:

trait T {
    type A;

    fn get(&mut self) -> Self::A;
}

struct Foo;

impl T for Foo {
    type A = i32;

    fn get(&mut self) -> i32 { 3 }
}

struct Wrapped<F, V> {
    func: F,
    cached: Option<V>,
}

impl<F, R> T for Wrapped<F, R::A>
    where F: FnMut() -> R,
          R: T,
          R::A: Copy,
{
    type A = R::A;

    fn get(&mut self) -> R::A {
        let v: R::A = self.cached.unwrap_or_else(|| (self.func)().get());
        self.cached = Some(v);
        v
    }
}

fn make_foo() -> Foo { Foo }

fn main() {
    let mut wrapped: Wrapped<fn() -> Foo, i32> = Wrapped {
        func: make_foo as fn() -> Foo,
        cached: None,
    };
    T::get(&mut wrapped);

    // the following does not compile: WHY?
    // wrapped.get();
}

Rust Playground

通用函数调用语法不应该与普通函数调用相同吗?

这是错误消息:

rustc 1.15.1 (021bd294c 2017-02-08)
error[E0284]: type annotations required: cannot resolve `<_ as T>::A == _`
  --> <anon>:44:13
   |
44 |     wrapped.get();
   |   

我知道问题源于我使用impl T<F, R::A>这一事实,即impl用于关联类型。通过避免这种相关类型,有一种解决方法:

struct Wrapped<R: T, F: FnMut() -> R> { func: F, cached: Option<R::A> }

但这不是我的问题。我对UFCS和普通函数调用之间的区别感兴趣。

0 个答案:

没有答案