Can I pass a function of an instance as a parameter to a function of the same instance, or do I have to pull the passed function out of the instance?
So, basically, does something like this work:
impl Some_Type {
fn some_fn(&self, value: u32) -> u32 {
value
}
fn some_other_fn(&self, value: u32, fn: &dyn Fn(&Self, u32) -> u32) -> u32 {
fn(value)
}
}
fn main() {
let instance = Some_Type::new();
let fourty_two = instance.some_other_fn(42, &instance.some_fn);
}
Or do I have to write it like this:
impl Some_Type {
fn some_other_fn(&self, value: u32, fn: &dyn Fn(&Self, u32) -> u32) -> u32 {
fn(value)
}
}
fn some_fn(&Some_Type, value: u32) -> u32 {
value
}
fn main() {
let instance = Some_Type::new();
let fourty_two = instance.some_other_fn(42, &some_fn);
}
I found a solution myself. One can write
fn main() {
let instance = Some_Type::new();
let fourty_two = instance.some_other_fn(42, &Some_Type.some_fn);
}
and pass &self
to fn
inside Some_Type.some_other_fn
in the first example.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.