by jdreaver · 10y ago · 0 comments
I don't use Rust, but your code examples look great! I understand that Rust has less opportunity for "magic" to clean things up (for example, in Python you can use a decorator to specify a route for a function), but otherwise it looks very clear. Awesome work!
#[route("/foobar")]
fn user(_: &mut Request) -> PencilResult {
// ...
}
However, procedural macros are unstable, but Rust is able to do amazing things with macros.Bearing in mind that macros er unstable, can this be done in Rust, and if so, what would the process be?
struct RouteUser {
route: &'static str,
f: fn(_: &mut Request) -> PencilResult
}
Then given #[route("/user")]
fn user(_: &mut Request) -> PencilResult {}
You would hijack the `user` function to return an instance of the struct. fn user() -> RouteUser {
// The actual function the user wrote:
fn user(_: &mut Request) -> PencilResult {
// ...
}
RouteUser {
// Generated from the annotation argument
route: "/user",
f: user
}
}
There is a difference between item decorators (`#[foobar]`) and regular procedural macros and I'm not completely sure if you could in-fact significantly change the given function. I haven't touched procedural macros in a while.To use the above route, you would simply have a `Route` trait perhaps.
trait Route {}
And implement it for each generated struct: impl Route for RouteUser {}
Then you could use the route as app.route(user());
Which could be defined as fn route<R>(r: R) where R: Route {
// ...
}I always look for the "Sinatra" of that language.
Rust is that thing exactly.