2017-03-17 68 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