2 stable releases
new 1.1.0 | Dec 21, 2024 |
---|---|
1.0.0 | Dec 19, 2024 |
#635 in Development tools
65 downloads per month
7KB
58 lines
Default Parameters
Do you want default function arguments or method parameters inside Rust?
Well, too bad! As this feature is currently not supported in Rust we can only emulate this functionality through macros and even more macros.
Formalisation
Default parameters could be easily formalised as
struct DefaultParam<T, const VAL: T>(T);
Reality
This approach however falls apart in a spectacular fashion as Rust doesn't support types dependent on other types.
Sadly this leaves us no choice. We can currently only make default arguments
for integer
, bool
and char
types.
How does this implementation work?
- All supported types have a wrapper around them (
i32 -> Di32
,bool -> Dbool
...) - Empty default arguments can be created via
let def1=Di32::<23>::new(); // Its value will be 23
- Default arguments with values can be created via
let def2=Di32::<5>::from(53); // Its value will be 53
- The value of default arguments can be unwrapped via
assert_eq!(def1.unwrap(),23);
assert_eq!(def2.unwrap(),53);