Difference between function and implementation method


#1

I would like to set up callbacks to member functions of an impl of a struct S.
Something along the lines of:

struct S;
impl S {
    fn my_callback(&self, x: u32) {
        // do something
    }
}

fn main() {
    let s = S;
    set_up_callback(s, S.my_callback); // cannot take value
}

I can see a way of doing that using a function outside of the struct, with type fn(&S, u32) or a Fn(&S, u32). I’m not sure of the difference between those two by the way? Is Fn (with capital F) for closures, and not fn?

The method outside the struct would then delegate to the “my_callback” method defined inside the impl. My first question is: is there a way to do this more simply? My second question is: what is the difference between a function taking a reference to the struct, say: fn(&S, u32) and a function implemented for the struct, say: fn(&self, u32)?


#2

S.my_callback initializes a new struct S, then calls the method my_callback on that. To refer to the function, use S::my_callback

Regular functions are of type fn(). The Fn() trait is implemented for functions, but also for closures.

When you define a method, there is a special syntax for the self parameter. self is the same as self: Self, &self is the same as self: &Self and &mut self is the same as self: &mut Self. They work just like regular functions and you can also call them as such:

assert_eq!("test".len(),str::len("test"))

#3

Wow that was fast and actually simple to do :slight_smile: I’m using :: for things like Vec::new, but somehow I didn’t think of using it here. Thanks for the explanations!