5

I am learning Rust. And investigating examples. Why does the code outputs 1? My code:

struct S {
    f: fn(),
}

impl S {
    fn f(&self) {
        print!("1");
    }
}


fn main() {
    let f2 = || print!("2");
    let s = S{f: f2};
    s.f(); // prints 1, but I expected 2

}


1 Answer 1

14

Rust distinguishes between methods defined on an impl block and fields associated with a struct. There is no relationship between the f in your S struct and the method whose full name is S::f which happens to take a &self argument.

s.f(); // Prints 1

This is syntax sugar for

S::f(&s); // Prints 1

It does not look at the fields of an object like Python does. When you have an expression followed by a method call syntax (i.e. a dot, a name, and an open parenthesis), that's always a method call. Method calls resolve statically and are treated as ordinary function calls by the runtime. s.f() could also refer to a method defined on a trait somewhere, if it were not defined in your inherent impl.

To call a function which happens to be stored in an instance variable, use extra parentheses.

(s.f)(); // Prints 2

This is not a method call. This is a field access, followed by calling the resulting field, which happens to be a function in this case.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.