struct Counter<T>
where
T: Fn() -> i32,
{
generator: T,
val: i32,
}
impl<T> Counter<T>
where
T: Fn() -> i32,
{
pub fn new(gen: T) -> Counter<T> {
Counter {
generator: gen,
val: 0,
}
}
pub fn next(&mut self) {
self.val = (self.generator)(); // This works
// self.val = self.generator(); // This does not work
}
pub fn get(&self) -> i32 {
self.val
}
}
The above is a small example where I am using a closure in a struct. When I call the closure via generator()
I get no method named generator found
. When I wrap it with ()
this does not happen. Why is that?
Types in Rust can have both a field and a method with the same name, e.g.
struct Foo {
bar: i32,
}
impl Foo {
fn bar(&self) -> i32 {
self.bar
}
}
fn main() {
let foo = Foo { bar: 42 };
dbg!(foo.bar());
}
It is a common convention to name getter methods after the field they get. The Rust language designers decided to avoid conflicts between field names and method names by having separate syntax to access them. An expression of the form foo.bar()
with parentheses always calls a method. An expression of the formfoo.bar
without directly adjacent parentheses references a field. As a consequence, you need additional parentheses around a field access expression if you want to call a function pointer stored in a field.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With