Are there any ways to recursively flatten tuples?

后端 未结 2 1617
醉梦人生
醉梦人生 2021-01-19 09:28

In Rust, is there any way to use traits and impls to (recursively) flatten tuples?

If it helps, something that works with N nested pairs is

2条回答
  •  天涯浪人
    2021-01-19 09:57

    I implemented this with specialization and auto trait.

    docs.rs

    github repo


    Usage is basically

    assert_eq!((1, (2, ((3,) (4, 5)), (), 6).flatten(), (1, 2, 3, 4, 5, 6));
    

    It removes all empty unit tuple () (like python).


    If you are writing generic code, you need to add

    where (A, B): Flatten
    

    rustc wants this because Flatten is implemented only if length of output tuple is smaller than 13.

提交回复
热议问题