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?
>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.