error[E0609]: no field `router` on type `&server::Server`
--> src\server.rs:103:9
|
103 | router.add_route(Method::Head, "/api/kv/:key", &self.hello_world);
| ^^^^^^
error[E0615]: attempted to take value of method `hello_world` on type `&server::Server`
--> src\server.rs:103:62
|
103 | router.add_route(Method::Head, "/api/kv/:key", &self.hello_world);
| ^^^^^^^^^^^ help: use parentheses to call the method: `hello_world(...)`
error: aborting due to 2 previous errors
My question is:
How to use a function pointer in implementation with a pointer function in the same impl ?
error[E0615]: attempted to take value of method `hello_world` on type `&server::Server`
--> src\server.rs:83:23
|
83 | let m = (self.hello_world)(self);
| ^^^^^^^^^^^ help: use parentheses to call the method: `hello_world(...)`
To get the function as a value you want to say Self::hello_world (you get a fn item which can be cast to a fn pointer if needed). I don't have the definition of hello_world, but it will be a function and if it has a self argument, it expects that as the first argument.
router.add_route expects a function, but (Self::hello_world)(self) is a value - the result of function evaluation. If you want to add a route with handler which always evaluates to the single value, you can try to make it explicitly through the closure:
fn router_api(&self) -> nickel::Router {
let mut router = Nickel::router();
let m = self.hello_world();
router.add_route(Method::Head, "/api/kv/:key", || m);
// or with some dummy arguments, like |_| m, - I can't find the signature for add_route
}
Ok, so the thing you need is some kind of partial application - supply the first argument (self) and let Nickel add the remaining ones. Looks like this should work:
fn router_api(&self) -> nickel::Router {
let mut router = Nickel::router();
let m = |req, res| self.hello_world(req, res);
router.add_route(Method::Head, "/api/kv/:key", m);
}
Or, if you prefer the more explicit way:
let m = |req, res| Self::hello_world(self, req, res);