Ilijanovic
Ilijanovic

Reputation: 14904

Get all arguments from function

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, ....);

Upvotes: 1

Views: 678

Answers (1)

Netwave
Netwave

Reputation: 42716

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"),
            },
        );
    }
}

Upvotes: 5

Related Questions