0

Basically I want to be able to store a function as a field in a struct, then call that function later. Fairly simple, but I can't figure out a good way to do it.

For example:

struct Car<'a> {
    wheels: i32,
    capacity: i32,
    drive: Box<dyn Fn() -> &'a str>
}

fn drive_car() -> &str {
    "vroom"
}

fn main {
    let car = Car {
        wheels: 4,
        capacity: 5,
        drive: drive_car()
    }

    car.drive()
}

So how can I go about making this happen. When I try to do this, I am the error message: no method named drive found for reference in the current scope from car.drive().

Sorry if there are a bunch of mistakes in there, still trying to learn rust.

Lee Morgan
  • 550
  • 1
  • 6
  • 26

1 Answers1

4

Your implementation is almost correct, some minor adjustments:

struct Car<'a> {
    wheels: i32,
    capacity: i32,
    drive: Box<dyn Fn() -> &'a str>,
}

pub fn drive_car() -> &'static str {
    "vroom"
}

You need to specify the lifetime in drive_car. You can now build Car as

fn main() {
    let car = Car {
        wheels: 4,
        capacity: 5,
        drive: Box::new(drive_car),
    };

    println!("{:?}", (car.drive)());
}

In other words, to call a function that is a field you write: (car.drive)().

Adam
  • 743
  • 1
  • 6
  • 11