Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why do I have to wrap a closure with ()?

Tags:

closures

rust

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?

like image 634
User12547645 Avatar asked Oct 17 '25 21:10

User12547645


1 Answers

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.

like image 191
Sven Marnach Avatar answered Oct 20 '25 17:10

Sven Marnach



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!