Misc 3 @WaffleLapkin @BoxyUwU
Warning: this quiz is still "work-in-progress", some questions might not have good explanations (or any at all), formatting/structure/titles/etc are not final, and so on. You might want to return here on a later date.
struct Foo {
func: fn(),
}
fn print_heheh() {
println!("ferrisUwu")
}
fn bar(foo: Foo) {
foo.func();
}
fn main() {
bar(Foo { func: print_heheh });
}
Solution
error[E0599]: no method named `func` found for struct `Foo` in the current scope
--> examples/misc_3.rs:10:9
|
1 | struct Foo {
| ---------- method `func` not found for this struct
...
10 | foo.func();
| ^^^^ field, not a method
|
help: to call the function stored in `func`, surround the field access with parentheses
|
10 | (foo.func)();
| + +
For more information about this error, try `rustc --explain E0599`.
error: could not compile `code` (example "misc_3") due to 1 previous error
There is a syntactic difference between a method call and a normal call. expr.identifier()
is always a method call and Foo
does not have a method called func
. To call the function stored in a field you need to add parenthesis:
fn bar(foo: Foo) {
(foo.func)();
}
Note that the same problem does not apply to tuples and tuple structs, because you can't name a method with an integer identifier. i.e. the following would compile:
struct Foo(fn());
fn print_heheh() {
println!("ferrisUwu")
}
fn main() {
let foo = Foo(print_heheh);
foo.0();
}