Access object-nonspecific methods of object's type

Hello,

I'm trying to figure out a technique for accessing object-nonspecific methods (i.e. methods that don't take self as the first argument) that are associated with the type of an object.

Consider this example: I'm hoping to be able to access the method default_closure associated with the type that variable table belongs to.

pub struct Table<const SIZE : usize> {
    
}

impl <const SIZE : usize>Table<SIZE> {
    
    pub fn default_closure() {
        println!("{}", SIZE);
    }
    
    // pub fn get_default_closure<'a, 'b, F : Fn()>(&'a self) -> &'b F {
    //     &Self::default_closure
    // }
    
    pub fn execute_closure<F : Fn()>(&self, closure : F) {
        closure();
    }
}

fn main() {
    
    let table : Table<3> = Table{};
    
    //This is bad because specifying the same constants between
    //the table object and the closure function is error-prone
    table.execute_closure(Table::<3>::default_closure);
    
    //Something like this would be better
    // table.execute_closure(table.type_of()::default_closure);
    
    //Or Something like this
    // table.execute_closure(table.get_default_closure());
}

Has anyone figured out a good way to do this?

Thanks in advance.

For this case, where there are no variable captures, you can just return a function pointer:

    pub fn get_default_closure(&self) -> fn() {
        Self::default_closure
    }

Edit: If there are captured variables, you can return an existential type (impl Fn):

    pub fn get_default_closure(&self, prefix:&'static str) -> impl Fn() {
        move || {
            print!("{} - ", prefix);
            Self::default_closure()
        }
    }
1 Like

Beautiful! Thank you!

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.