-1

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?

WiseEye
  • 133
  • 9

1 Answers1

1

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.

  • 1
    awesome, thanks! No, I am not in undergrad :P – WiseEye Nov 26 '22 at 04:26
  • In the struuct you define that the is one uszie parameter and one only, what if I want my objects being created to have more, less, or different parameters... i.e., my Honda might need an oil type to be passed in while the Tesla should not. – WiseEye Nov 26 '22 at 04:29
  • might want to look at generics – Tengku Izdihar Dec 02 '22 at 11:29