Crate variadics

source ·
Expand description

§Variadics

Variadic generics in stable Rust

§Variadic Generics?

Variadic generics are one of the most discussed potential Rust features. They would enable traits, functions, and data structures to be generic over variable length tuples of arbitrary types.

Currently you can only implement generic code for tuples of a specific length. If you want to handle tuples of varying lengths you must write a separate implementation for each length. This leads to the notorious limitation that traits in Rust generally only apply for tuples up to length 12.

Variadic generics allow generic code to handle tuples of any length.

§Tuple lists

Although variadic generics fundamentally require changing the Rust compiler, we can emulate pretty well with tuple lists.

Any tuple (A, B, C, D) can be mapped to (and from) a recursive tuple (A, (B, (C, (D, ())))).

Each element consists of a nested pair (Item, Rest), where Item is tuple element and Rest is the rest of the list. For last element Rest is a unit tuple (). Unlike regular flat tuples, these recursive tuples can be effectively reasoned about in stable Rust.

You may recognize this fundamental structure from cons lists in Lisp as well as HLists in Haskell.

This crate calls these lists “variadics” and provides traits and macros to allow simple, ergonimc use of them.

§Usage

var_expr! creates variadic values/expressions, var_type! creates variadic types, and var_args! creates variadic patterns (used in unpacking arguments, on the left side of let declarations, etc.).

These macros support the “spread” syntax ..., also known as “splat”. For example, var_expr!(a, ...var_b, ...var_c, d) will concatenate a, the items of var_b, the items of var_c and d together into a single variadic list.

§Acknowledgements

This crate is based on tuple_list by VFLashM, which is MIT licensed:

MIT license
Copyright (c) 2020 Valerii Lashmanov

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE
 

§Main Macros

§var_expr!

Variadic expressions (values) macro.

Creates a variadic tuple value from a list of expressions.

Create a variadic tuple value:

use variadics::var_expr;

let list = var_expr!(10, false, "foo");

assert_eq!(list, (10, (false, ("foo", ()))),)

Although this can be used as a pattern to unpack tuples, var_args! should be used instead:

// Ok...
let var_expr!(a, b, c) = var_expr!(10, false, "foo");
// Better:
let var_args!(a, b, c) = var_expr!(10, false, "foo");

assert_eq!(a, 10);
assert_eq!(b, false);
assert_eq!(c, "foo");

The “spread” (or “splat”) syntax ... can be used to concatenate variadics together:

let list_a = var_expr!(0.5, "foo");
let list_b = var_expr!(-5, false);
// Spread syntax:
let list_c = var_expr!(...list_a, ...list_b, "bar");
// Equals `var_expr!(0.5, "foo", -5, false, "bar)`.

§var_type!

Variadic types macro.

Creates a variadic tuple type from a list of types.

var_expr! can be used to define simple types but will result in confusing errors for more complex types. Use this macro, var_type! instead.

use variadics::{var_expr, var_type};

// A simple variadic type. Although `var_expr!` would work in this case, it cannot handle
// more complex types i.e. ones with generics.
let list: var_type!(i32, bool, String) = Default::default();

// A more complex type:
let list: var_type!(
    &'static str,
    HashMap<i32, i32>,
    <std::vec::Vec<bool> as IntoIterator>::Item,
) = var_expr!("foo", HashMap::new(), false);

The “spread” (or “splat”) syntax ... can be used to concatenate variadics together:

type ListA = var_type!(f32, &'static str);
type ListB = var_type!(i32, bool);
// Spread syntax:
type ListC = var_type!(...ListA, ...ListB, Option::<()>);
// Equals `var_type!(f32, &'static str, i32, bool, Option::<()>)`.

Unfortunately, expressions and types cannot be handled using the same macro due to the undefeated bastion of the turbofish.

§var_args!

Variadic patterns macro.

Used to pattern-match or “unpack” variadic tuples. This is used for function arguments, as well as in match, if/while let ..., let ... else, and for expressions.

Although it may somtimes be possible to use var_expr! in place of this macro, doing so may cause confusing errors.

use variadics::{var_args, var_expr, var_type};

fn my_fn(var_args!(a, b, c): var_type!(usize, &str, bool)) {
    println!("{} {} {}", a, b, c);
}
my_fn(var_expr!(12, "hello", false));
use variadics::{var_args, var_expr};

let val = var_expr!(true, Some("foo"), 2);
if let var_args!(true, Some(item), 0..=3) = val {
    println!("{}", item);
} else {
    unreachable!();
}
match var_expr!(true, Some(100), 5) {
    var_args!(false, _, _) => unreachable!(),
    var_args!(true, None, _) => unreachable!(),
    var_args!(true, Some(0..=10), _) => unreachable!(),
    var_args!(true, Some(a), b) => println!("{} {}", a, b),
}

The “spread” (or “splat”) syntax ... can be used to unpack the tail of a variadic. Note that unlike with the other macros, this macro (var_args!) only allows the spread syntax on the final argument.

let var_args!(a, b, ...list_c) = var_expr!("hi", 100, 0.5, false);
assert_eq!(var_expr!(0.5, false), list_c);

Macros§

  • Variadic patterns macro.
  • Variadic expressions (values) macro.
  • Variadic types macro.
  • This macro generates a basic variadic trait where each element must fulfill the where clause.

Traits§