Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Pass a function to an object as creation parameter

I am creating an object of tesla, that comes from the struct of Car.

The way each car gets energy to work is different, in the case of a Tesla, we plug in a cable and pass electricity, in the case of a Honda, we insert oil into a tank. I want my car struct to have a property of get_energy with a Fn datatype, so that when I create a new car I can pass in a function that will be called when I call tesla.get_energy()… the creation of tesla would ideally be something like let tesla = Car(get_energy: || => {grab_cable(), insert_cable(), pass_electricty()}) which would look different from the creation of a Honda. Can I somehow do that?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

For the love of god I hope I’m not answering an undergrad’s homework.

But assuming good faith, this is my approach. I would probably store that function/closure and box it. It will look like this.

struct Foo {
    pub foo: Box<dyn Fn(usize) -> usize>,
}

impl Foo {
    fn new(foo: impl Fn(usize) -> usize + 'static) -> Self {
        Self { foo: Box::new(foo) }
    }
}

fn main() {
    let foo = Foo {
        foo: Box::new(|a| a + 1),
    };
    (foo.foo)(42);
    
    (Foo::new(|a| a + 1).foo)(42);
}

I of course stole it from here How do I store a closure in a struct in Rust?. Not going to flag the question yet because I’m not used to stackoverflow.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading