您还不能实施Fn*
稳定 Rust 的特征。这只能通过使用夜间编译器来实现#[feature]
!
这非常有用充分阅读您正在实施的特征看看如何实现它。这Fn trait https://doc.rust-lang.org/std/ops/trait.Fn.html定义为:
pub trait Fn<Args>: FnMut<Args> {
extern "rust-call" fn call(&self, args: Args) -> Self::Output;
}
注意到实现和定义之间有什么区别吗?我看到很多:
该实现没有提供价值Args
!这就是编译器所指出的。也可以看看类型参数数量错误:预期为 1,但发现为 0 https://stackoverflow.com/q/25272392/155423
该实现没有实现超级特征FnMut https://doc.rust-lang.org/std/ops/trait.FnMut.html,这本身就需要超特质FnOnce https://doc.rust-lang.org/std/ops/trait.FnOnce.html. FnOnce
是哪里关联类型 Output
被宣布。
该实现忽略了定义具体类型Output
应该。
执行返回Self
当特质回归时Self::Output
.
该实现不接受第二个参数call
。该参数包含传入的任何参数。
此外,Rust 中的类型使用PascalCase
, not 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)
}
也可以看看:
- 什么是 crate 属性以及在哪里添加它? https://stackoverflow.com/q/27454761/155423