gpt4 book ai didi

methods - 如何通过函数指针调用方法?

转载 作者:行者123 更新时间:2023-11-29 08:12:01 24 4
gpt4 key购买 nike

<分区>

使用函数指针调用对象方法的正确语法是什么?

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 类型使用正确的类型;什么是正确的类型?

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com