1

I am currently working on a web server app:

mod rustex;
use rustex::Response;

fn main() {
    let bind_address = "127.0.0.1:8080";

    let mut app = rustex::App::new(bind_address);

    app.get("/hello", || -> Response {
        Response {
            data: String::from("hello"),
            status: 200,
        }
    });

    app.run_server();
}

My .get() method looks like this:

pub fn get(&mut self, path: &str, handler: fn() -> Response) {
    self.routes.insert(
        path.to_owned(),
        RouteOption {
            handler,
            method: String::from("GET"),
        },
    );
}

I was wondering if i could pass multiple functions inside.get() and get a list of it. I javascript you would do something like:

function get(path, ...handlers) {
   //handlers is an array with your arguments
}

Is this possible or do i need to pass an Array as second argument?

What i want is to pass as many handlers as i want like:

    app.get("/hello", handler1, handler2, ....);
bill.gates
  • 14,145
  • 3
  • 19
  • 47
  • Does this answer your question? [How can I create a function with a variable number of arguments?](https://stackoverflow.com/questions/28951503/how-can-i-create-a-function-with-a-variable-number-of-arguments) – Chayim Friedman Jun 01 '22 at 20:23

1 Answers1

4

Variable args are not allowed in rust (as per rust 1.63): Consider sharing an slice instead:

pub fn get(&mut self, path: &str, handlers: &[fn() -> Response]) {
    for handler in handlers.into_iter() {
        self.routes.insert(
            path.to_owned(),
            RouteOption {
                handler,
                method: String::from("GET"),
            },
        );
    }
}
Netwave
  • 40,134
  • 6
  • 50
  • 93