2017-03-17 19 views
2
#![feature(unboxed_closures)] 
#![feature(fn_traits)] 

struct foo; 

impl std::ops::Add for foo { 
    type Output = foo; 
    fn add(self, x: foo) -> foo { 
     println!("Add for foo"); 
     x 
    } 
} 

impl Fn for foo { 
    extern "rust-call" fn call(&self) -> Self { 
     println!("Call for Foo "); 
     self 
    } 
} 

fn main() { 
    let x = foo; 
    let y = foo; 
    x + y; 

    x(); 
} 

我實現了Add特質,但我不明白如何調用該結構作爲函數。我收到錯誤:如何使結構可調用?

error[E0243]: wrong number of type arguments: expected 1, found 0 
    --> src/main.rs:14:10 
    | 
14 |  impl Fn for foo { 
    |   ^^ expected 1 type argument 

我是Rust的新手,無法找到如何使這件事發生的示例。

回答

7

這對充分了解您正在實施的特徵以瞭解如何實施它。 Fn trait被定義爲:

pub trait Fn<Args>: FnMut<Args> { 
    extern "rust-call" fn call(&self, args: Args) -> Self::Output; 
} 

請注意實現和定義之間的區別?我看到很多:

  1. 該實現不爲Args提供值!這正是編譯器所指的。另請參見Wrong number of type arguments: expected 1 but found 0

  2. 該實現不實現超級杆FnMut,該超級杆本身需要超級杆FnOnceFnOnce關聯的類型Output被聲明。

  3. 該實現忽略了定義具體類型Output應該是什麼。

  4. 執行返回Self而特徵返回Self::Output

  5. 該實現不接受call的第二個參數。此參數包含在傳遞的任何參數。

此外,類型拉斯特使用PascalCase,不snake_case,所以應該是Foo

#![feature(unboxed_closures)] 
#![feature(fn_traits)] 

struct Foo; 

impl Fn<()> for Foo { 
    extern "rust-call" fn call(&self, _args:()) { 
     println!("Call (Fn) for Foo"); 
    } 
} 

impl FnMut<()> for Foo { 
    extern "rust-call" fn call_mut(&mut self, _args:()) { 
     println!("Call (FnMut) for Foo"); 
    } 
} 

impl FnOnce<()> for Foo { 
    type Output =(); 

    extern "rust-call" fn call_once(self, _args:()) { 
     println!("Call (FnOnce) for Foo"); 
    } 
} 

fn main() { 
    let x = Foo; 
    x(); 
} 

通常情況下,雖然,只有一個特徵的實施將有有趣的代碼,它和其他的特徵實現將委託給它:

extern "rust-call" fn call(&self, args:()) { 
    println!("Foo called, took args: {:?}", args); 
} 

// ... 

extern "rust-call" fn call_mut(&mut self, args:()) { 
    self.call(args) 
} 

// ... 

extern "rust-call" fn call_once(self, args:()) { 
    self.call(args) 
} 
+0

非常感謝!非常好的解釋。 –

+0

@АндрейЛедовских歡迎您。請記住提出有用的答案,並接受最能幫助您解決問題的答案。 – Shepmaster