I'm a beginner studying Rust.
I'd like to create a function that receives structural methods, but I can't pass them to the function, so please give me some advice.
Receive Function - Rust by Example
I created the following code by referring to .
execute(function,&s); is running, but the following error appears in the
However, what you want to do is not
execute(foo.method(&foo.s); to "pass the return value of the method to the function."
How do I pass the structural method to a function?
Thank you for your cooperation.
If you specify a closure, you can do what you want (although the amount of description increases).
If you want to pass the function itself:
However, since the
method function takes two arguments:
s, the function that receives the method needs to be modified.
There is another problem with the code you are asking, besides
execute(foo.method, & foo.s).Let's fix it in order.
First, the argument for the
This is the
Fn(&String) type.This is a closure that takes only one argument.
method method in
Foo has the following definition and takes two arguments:
method is of type
Fn(&Foo,&String) and cannot be passed to the argument
Fn(&String) for the
Let's fix this first.
In the first place,
Foo has the field
s:String, so you do not need to take another
s as an argument, such as
fn method(&self, s:&String).Make the following changes:
method is now of the
Fn(&Foo) type with only one argument.
Then modify the
execute function.Change the second argument
s:&String to accept any type
This allows you to take both the
method of type
Fn(&Foo) and the
function of type
Fn(&String) as arguments.
Finally, let's correct the code below that was originally an error.
Rust's method is only one of the related functions. If
foo is of type
Foo, you write
foo.method(), the compiler assumes that
Foo::method(&foo).Therefore, you can write as follows.
You will now be able to compile.The results are as follows:
The overall code is as follows:
© 2023 OneMinuteCode. All rights reserved.