Rust default and keyword macro
Example
Basic example of using default arguments:
use ;
default_args!
Like in the most languages that have this feature, positional argument have to come before any arguments with default value.
Limitations
-
No variadics (
fn foo(a: f64, ...)) -
Complex patterns don't work, i.e.
Point(x, y): Point = Point(5, 20)would produce an error. -
You will have to pass defaulted arguments only using keywords. That is, you can't do this:
use ; default_args! -
At least for now, it is required that you use full function path in the
keyword_argsmacro. The reason is that we can't get the full path to the args struct from the name of the function. This might change in the future.
How does it work
Basically, the default_args macro generates a new struct and implements
Default for it based on function's name.
The example above expands to roughly this:
And keyword_args does the opposite:
Credits
Thank you @dtolnay for an amazing work in parsing and macro ecosystems:
- syn
- quote
- cargo-expand
- and many others!
License
MIT or Apache License, Version 2.0 at your option.