Rust 如何使结构可调用?
我实现了Rust 如何使结构可调用?,rust,implementation,traits,Rust,Implementation,Traits,我实现了Add特性,但我不知道如何将结构作为函数调用。我得到一个错误: error[E0243]:类型参数数量错误:应为1,找到0 -->src/main.rs:14:10 | 14 |对foo的建议{ |^^应为1个类型参数 我是个新手,找不到如何实现这一点的例子。你还不能在stable Rust中实现Fn*特性。这只有在每晚使用.[feature]的编译器中才能实现 全面阅读您正在实现的特性,了解如何实现它,这是非常有用的。定义如下: #![feature(unboxed_closures
Add
特性,但我不知道如何将结构作为函数调用。我得到一个错误:
error[E0243]:类型参数数量错误:应为1,找到0
-->src/main.rs:14:10
|
14 |对foo的建议{
|^^应为1个类型参数
我是个新手,找不到如何实现这一点的例子。你还不能在stable Rust中实现
Fn*
特性。这只有在每晚使用.[feature]
的编译器中才能实现
全面阅读您正在实现的特性,了解如何实现它,这是非常有用的。定义如下:
#![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();
}
但通常情况下,只有一个trait的实现会包含有趣的代码,而其他trait实现会委托给它:
#![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();
}
另见:
fn main(){
设func:Functionish=make_func();
func();
}
fn make_func()->Functionish{
功能性{
f:Box::new(| | println!(“打印”),
}
}
结构函数{
f:盒子,
}
Functionish的impl std::ops::Deref{
类型Target=dyn-Fn();
fn deref(&self)->&self::Target{
&赛尔夫
}
}
这里有一个不完整的示例,来自我自己的代码,它接受参数,一个是ref,一个是可变ref。在我的例子中,闭包存储在一个Rc中,这需要奇数行&(*self.function_container)
,因为我需要进入Rc才能获得闭包的引用
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)
}
pub-struct-FeelFunction{
发布函数类型:函数类型,
容器名称:RefCell,
功能容器:Rc FeelValue>
}
FeelFunction的impl-Deref{
类型Target=dyn-Fn(&FeelValue,&mut-NestedContext)->FeelValue;
fn deref(&self)->&self::Target{
&(*自功能容器)
}
}
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)
}
pub struct FeelFunction {
pub function_type: FunctionType,
name_container: RefCell<String>,
function_container: Rc<dyn Fn(&FeelValue, &mut NestedContext) -> FeelValue>
}
impl Deref for FeelFunction {
type Target = dyn Fn(&FeelValue, &mut NestedContext) -> FeelValue;
fn deref(&self) -> &Self::Target {
&(*self.function_container)
}
}