使用函数指针在对象上调用方法的正确语法是什么?
struct Foo {
var: i32,
}
impl Foo {
fn method(&mut self, arg: i32) {
self.var = self.var + arg;
println!("var = {}", self.var);
}
}
fn main() {
let foo = Foo { var: 11 };
let func_ptr: Fn() = &foo.method;
(func_ptr).method(12);
}
我收到此错误:
error[E0615]: attempted to take value of method `method` on type `Foo`
--> src/main.rs:14:31
|
14 | let func_ptr: Fn() = &foo.method;
| ^^^^^^ help: use parentheses to call the method: `method(...)`
error[E0599]: no method named `method` found for type `dyn std::ops::Fn()` in the current scope
--> src/main.rs:15:16
|
15 | (func_ptr).method(12);
| ^^^^^^
|
= note: (func_ptr) is a function, perhaps you wish to call it
error[E0277]: the size for values of type `dyn std::ops::Fn()` cannot be known at compilation time
--> src/main.rs:14:9
|
14 | let func_ptr: Fn() = &foo.method;
| ^^^^^^^^ doesn't have a size known at compile-time
|
= help: the trait `std::marker::Sized` is not implemented for `dyn std::ops::Fn()`
= note: to learn more, visit <https://doc.rust-lang.org/book/ch19-04-advanced-types.html#dynamically-sized-types-and-the-sized-trait>
= note: all local variables must have a statically known size
= help: unsized locals are gated as an unstable feature
我猜我没有为func_ptr
类型使用正确的类型;什么是正确的类型?
答案 0 :(得分:4)
方法不绑定self
参数,但是您可以通过其完全限定的名称访问方法,并且可以根据需要将它们保存在函数指针中。稍后,当您调用函数指针时,您必须自己提供self
参数:
struct Foo {
var: i32,
}
impl Foo {
fn method(&mut self, value: i32) {
self.var += value;
println!("var = {}", self.var);
}
}
fn main() {
let mut foo = Foo { var: 11 };
let func_ptr = Foo::method;
func_ptr(&mut foo, 12);
}
如果您想手动定义此局部变量的类型,则它将是以下内容:
let func_ptr: fn(&mut Foo, i32) = Foo::method;
如果要使用特征符号,则必须在参考后面使用它:
let func_ptr: &Fn(&mut Foo, i32) = &Foo::method;