https://github.com/maikklein/variadic
Variadics in stable Rust
https://github.com/maikklein/variadic
Last synced: 6 months ago
JSON representation
Variadics in stable Rust
- Host: GitHub
- URL: https://github.com/maikklein/variadic
- Owner: MaikKlein
- Created: 2016-10-06T16:50:58.000Z (about 9 years ago)
- Default Branch: master
- Last Pushed: 2016-10-06T17:12:20.000Z (about 9 years ago)
- Last Synced: 2025-03-29T08:02:36.647Z (6 months ago)
- Language: Rust
- Homepage:
- Size: 2.93 KB
- Stars: 2
- Watchers: 0
- Forks: 1
- Open Issues: 0
-
Metadata Files:
- Readme: README.md
Awesome Lists containing this project
README
# Not yet functional
## Overview
This is just a little fun project and should probably not be used in production. Currently variadics are only implemented up to a dimension of `4`. `Variadic`'s are only pssible because of default types and I consider this implementaion a `hack`.
`Variadic` is the trait that makes variadic arguments possible in stable Rust. `VarArgs1`, `VarArgs2` etc implement `Variadic` which allows the user the call `pop()`.
`pop` will return the first argument inside an `Option` and another `VarArgs(n-1)`. For example
~~~
let (Some(value), rest: VarArgs2) = VarArgs3(1, 2, 3).pop();
~~~## Examples:
A simple sum example implemented with recursion.
~~~
fn sum>(args: Args) -> i32 {
if let (Some(front), rest) = args.pop() {
front + sum(rest)
} else {
0
}
}
println!("sum: {}", sum(VarArgs4(1, 2, 3, 4)));
~~~Here we call `pop` on `VarArgsN` and it will return `(Option, VarArgs(N-1))`. The recursion stops at `VarArgs0` which returns a `(Option, VarArgs0)` where `Option` will always be `None`.
~~~
fn fact>(args: Args) -> i32 {
if let (Some(front), rest) = args.pop() {
front * fact(rest)
} else {
1
}
}
println!("fact: {}", fact(VarArgs4(1, 2, 3, 4)));
~~~It is also possible to use traits with `Variadic`. Here we constrain `T` with `std::fmt::Debug`, then we print out every value that we `pop` off until we reach `VarArgs0`.
~~~
fn debug_print>(args: Args)
where T: std::fmt::Debug
{
if let (Some(front), rest) = args.pop() {
println!("{:?}", front);
debug_print(rest);
}
}debug_print(VarArgs3(1, 2, 3));
~~~