# Thoughts on tuples

**URL:** <https://internals.rust-lang.org/t/thoughts-on-tuples/18778>\
**Category:** language design\
**Created:** [May 3, 2023, 4:25pm UTC](https://internals.rust-lang.org/t/thoughts-on-tuples/18778 "2023-05-03T16:25:44Z")\
**Posts on this page:** 20\
**Page:** 1

<div class="post-metadata">

**Author:** ![Massou](https://sea2.discourse-cdn.com/flex002/user_avatar/internals.rust-lang.org/massou/32/10103_2.png) [@Massou](https://internals.rust-lang.org/u/Massou)\
**Post date:** [May 3, 2023, 4:25pm UTC](https://internals.rust-lang.org/t/thoughts-on-tuples/18778/1 "2023-05-03T16:25:44Z")

</div>

Hello, after using rust for quite some time, I've realized that I missed some features related to tuples.

I've implemented some of the features I miss [here](https://github.com/cantina-space/tuplify), but there are few things that I wanted to do that probably need some new language features.

Below some pseudo code to illustrate what I still miss.

Ability to bind by pattern a subset of a tuple:

```rust
let (a, b @ .., c) = ("some", "tuple", "stuff", 1);

assert_eq!(b, ("tuple", "stuff"));

```

const loops/loop unrolling with tuples (not sure if it's the correct wording here):

```rust

let mut tupl = (1, 2, 3, 4);

const while let Some((head, tail)) = tupl.uncons_opt() {
    if do_something(head) {
        tupl = tail;
    } else {
        tupl = ();
    }
}

// which would be expanded to

let (a, b, c, d) = (1, 2, 3, 4);
if do_something(a) {
    if do_something(b) {
        if do_something(c) {
            do_something(d);
        }
    }
}

```

Constraints on tuple members

```rust

trait SomeTrait {}

struct Foo;

impl SomeTrait for Foo {}

struct Bar;

impl SomeTrait for Bar {}

struct Baz;

fn do_something(t: impl TupleOf<SomeTrait>) {}

do_something((Foo, Bar)); // compiles
do_something((Foo, Bar, Baz)); // compile error

```

With all of those combined I think that this would be mostly equivalent to variadic generics.

I was wondering if this is worth a discussion since I have not seen one (sorry if that's not the case, it slipped under my radar).

EDIT: I've added more examples [here](https://gist.github.com/PoignardAzur/aea33f28e2c58ffe1a93b8f8d3c58667?permalink_comment_id=4558908#gistcomment-4558908)

---

<div class="post-metadata">

**Author:** ![Jules-Bertholet](https://sea2.discourse-cdn.com/flex002/user_avatar/internals.rust-lang.org/jules-bertholet/32/10671_2.png) [@Jules-Bertholet](https://internals.rust-lang.org/u/Jules-Bertholet)\
**Post date:** [May 3, 2023, 9:22pm UTC](https://internals.rust-lang.org/t/thoughts-on-tuples/18778/2 "2023-05-03T21:22:27Z")

</div>

Variadics have been discussed many times before, most recently in the context of [A Mirror for Rust: Compile-Time Reflection Report - Shepherd's Oasis](https://soasis.org/posts/a-mirror-for-rust-a-plan-for-generic-compile-time-introspection-in-rust/). IMO [Analysising variadics, and how to add them to Rust · PoignardAzur](https://poignardazur.github.io/2021/01/30/variadic-generics/) is a good overview of the design space.

---

<div class="post-metadata">

**Author:** ![Massou](https://sea2.discourse-cdn.com/flex002/user_avatar/internals.rust-lang.org/massou/32/10103_2.png) [@Massou](https://internals.rust-lang.org/u/Massou)\
**Post date:** [May 4, 2023, 2:55pm UTC](https://internals.rust-lang.org/t/thoughts-on-tuples/18778/3 "2023-05-04T14:55:51Z")

</div>

thanks for your answer. I've read the posts you linked.

When I said `I was wondering if this is worth a discussion since I have not seen one` I was refering to using tuples directly not having variadic generics that can use tuples.

after some search and readings:

> <https://github.com/rust-lang/rfcs/issues/376>
>
> \<a href="https://github.com/eddyb"\>\<img src="https://avatars.githubusercontent.c…om/u/77424?v=2" align="left" width="96" height="96" hspace="10"\>\</img\>\</a\> \*\*Issue by \[eddyb\](https://github.com/eddyb)\*\*
> \_Monday Oct 28, 2013 at 17:39 GMT\_
> 
> \_For earlier discussion, see https://github.com/rust-lang/rust/issues/10124\_
> 
> \_This issue was labelled with: B-RFC in the Rust repository\_
> 
> \---
> \## The Problem
> \- \[fn types need a reform\](http://smallcultfollowing.com/babysteps/blog/2013/10/10/fn-types-in-rust/), and being able to define a trait with a variable number of type parameters would help
> \- working with functions which have a variable number of arguments is impossible right now (e.g. a generic \`bind\` method, \`f.bind(a, b)(c) == f(a, b, c)\`) and defining such functions may only be done (in a limited fashion) with macros
> \- tuples also have similar restrictions right now, there is no way to define a function which takes any tuple and returns the first element, for example
> \## The Solution: Part One
> 
> C++11 sets a decent precedent, with its variadic templates, which can be used to define type-safe variadic functions, among other things.
> I propose a similar syntax, a trailing \`..T\` in generic formal type parameters:
> 
> \`\`\` rust
> type Tuple\<..T\> = (..T); // the parens here are the same as the ones around a tuple.
> // use =\> expansion
> Tuple\<\> =\> ()
> Tuple\<int\> =\> (int,)
> Tuple\<A, B, C\> =\> (A, B, C)
> \`\`\`
> 
> The simple example above only uses \`..T\`, but not \`T\` itself.
> The question which arises is this: what is \`T\`? C++11 has a special case for variadic parameter packs, but we can do better.
> We have tuples. We can use them to store the actual variadic generic type parameters:
> 
> \`\`\` rust
> // Completely equivalent definition:
> type Tuple\<..T\> = T;
> // Detailed expansion of (..T) from above:
> Tuple\<\> =\> (..()) =\> ()
> Tuple\<int\> =\> (..(int,)) =\> (int,)
> Tuple\<A, B, C\> =\> (..(A, B, C)) =\> (A, B, C)
> \`\`\`
> \## The Solution: Part Two
> 
> Now that we know the answer is "tuples", everything else is about extending them.
> The prefix \`..\` operator would expand a tuple type:
> 
> \`\`\` rust
> // in another tuple type:
> type AppendTuple\<T, U\> = (..T, U);
> type PrependTuple\<T, U\> = (U, ..T);
> AppendTuple\<PrependTuple\<Tuple\<B\>, A\>, C\> =\> (A, B, C)
> // in a fn type's parameter list:
> type VoidFn\<..Args\> = fn(..Args);
> VoidFn\<A, B, C\> =\> fn(A, B, C);
> // in a variadic generic parameter list:
> Tuple\<..(A, B, C), ..(D, E, F)\> =\> (A, B, C, D, E, F)
> \`\`\`
> 
> Then we can do the same thing with values:
> 
> \`\`\` rust
> // in another tuple:
> (..(true, false), ..(1, "foo"), "bar") =\> (true, false, 1, "foo", "bar")
> // in a function call:
> f(..(a, b), ..(c, d, e), f) =\> f(a, b, c, d, e, f)
> \`\`\`
> 
> There's only one piece missing: we're still not able to define a function which takes a variable number of arguments.
> For this, I propose \`..x: T\` (where T is a tuple type) in a pattern, which can be used to "capture" multiple arguments when used in fn formal arguments:
> 
> \`\`\` rust
> // Destructure a tuple.
> let (head, ..tail) = foo;
> // This function has the type fn(int, A, B, C), and can be called as such:
> fn bar(\_: int, ..x: (A, B, C)) -\> R {...}
> \`\`\`
> 
> A type bound for \`..T\` (i.e. \`impl\<..T: Trait\>\`) could mean that the tuple \`T\` has to satisfy the bound (or each type in \`T\`, but that's generally less useful).
> \## Examples:
> 
> \`\`\` rust
> // The highly anticipated Fn trait.
> trait Fn\<Ret, ..Args\> {
> fn call(self, ..\_: Args) -\> Ret;
> }
> impl Fn\<Ret, ..Args\> for fn(..Args) -\> Ret {
> fn call(self, ..args: Args) -\> Ret {
> self(..args)
> }
> }
> impl Fn\<Ret, ..Args\> for |..Args| -\> Ret {
> fn call(self, ..args: Args) -\> Ret {
> self(..args)
> }
> }
> 
> // Cloning tuples (all cons-list-like algorithms can be implemented this way).
> impl\<Head, ..Tail: Clone\> Clone for (Head, ..Tail) {
> fn clone(&self @ &(ref head, ..ref tail)) -\> (Head, ..Tail) {
> (head.clone(), ..tail.clone())
> }
> }
> impl Clone for () {
> fn clone(&self) -\> () {
> ()
> }
> }
> 
> // Restricting all types in a variadic tuple to one type.
> trait ArrayLikeTuple\<T\> {
> fn len() -\> uint;
> }
> impl\<T\> ArrayLikeTuple\<T\> for () {
> fn len() -\> uint {0}
> }
> impl\<T, ..Tail: ArrayLikeTuple\<T\>\> ArrayLikeTuple\<T\> for (T, ..Tail) {
> fn len() -\> uint {
> 1 + Tail::len()
> }
> }
> 
> // And using that trait to write variadic container constructors.
> impl\<T\> Vec\<T\> {
> fn new\<..Args: ArrayLikeTuple\<T\>\>(..args: Args) -\> Vec\<T\> {
> let v: Vec\<T\> = Vec::with\_capacity(Args::len());
> // Use an unsafe move\_iter-like pattern to move all the args
> // directly into the newly allocated vector. 
> // Alternatively, implement &move \[T\] and move\_iter on that.
> }
> }
> 
> // Zipping tuples, using a \`Tuple\` kind and associated items.
> trait TupleZip\<Other\>: Tuple {
> type Result: Tuple;
> fn zip(self, other: Other) -\> Result;
> }
> impl TupleZip\<()\> for () {
> type Result = ();
> fn zip(self, \_: ()) -\> () {}
> }
> impl\<A, ATail: TupleZip\<BTail\>, B, BTail: Tuple\> TupleZip\<(B, ..BTail)\> for (A, ..ATail) {
> type Result = ((A, B), ..ATail::Result);
> fn zip(self @ (a, ..a\_tail), (b, ..b\_tail): (B, ..BTail)) -\> Result {
> ((a, b), ..a\_tail.zip(b\_tail))
> }
> }
> \`\`\`
> \## Todo
> \- better formal descriptions
> \- figure out the details of pattern matching
> \- more examples

> <https://github.com/rust-lang/rfcs/pull/1935>
>
> \[Rendered\](https://github.com/cramertj/rfcs/blob/variadic-generics/text/0000-var…iadic-generics.md)
> 
> cc @eddyb @sgrif

> <https://github.com/rust-lang/rfcs/pull/2775>
>
> This RFC introduce variadic tuples, and API to handle tuples with an arbitrary a…rity.
> 
> \[Rendered\](https://github.com/fredpointzero/rfcs/blob/variadic\_tuples/text/0000-variadic-tuples.md)
> \[Internal's thread\](https://internals.rust-lang.org/t/pre-rfc-variadic-tuple/10878)

It seems that there is no definitive consensus on this, but similar ideas have already emerged.

I'm wondering if this is the right time to bring back this topic and if I should comment in the open draft rfc on github.

The internals forum seemed the right place to me but I don't know if I'm mistaken (should I create an account on zulip ?, ask specific persons ?). I can contribute to the effort if I'm allowed to.

I have no knowledge related to the compiler internals so I've no idea on the feasibility of what I'm suggesting.

---

<div class="post-metadata">

**Author:** ![afetisov](https://sea2.discourse-cdn.com/flex002/user_avatar/internals.rust-lang.org/afetisov/32/8508_2.png) [@afetisov](https://internals.rust-lang.org/u/afetisov)\
**Post date:** [May 4, 2023, 3:41pm UTC](https://internals.rust-lang.org/t/thoughts-on-tuples/18778/4 "2023-05-04T15:41:02Z")

</div>

I think the things you propose are so close to variadics, that it doesn't make sense to consider them in isolation. The most natural context where stuff like tuple subslicing would be important is exactly variadic tuple context. For concrete tuples, you can always write out this transformation manually, even if it may be slightly verbose. And stuff like

```rust
fn do_something(t: impl TupleOf<SomeTrait>) {}

```

is basically variadics with a different syntax.

If you decide to pursue variadics, I would suggest leaving things like `const while let` out of your proposals. This is an orthogonal feature, with applications which go far beyond variadic tuples (even if those give a natural use case), and likely with very complex design and implementation of its own. Trying to pull in some sort of Zig-like or D-like comptime into Rust is a huge endeavor which is likely to tank any proposal it gets attached to.

---

<div class="post-metadata">

**Author:** ![Massou](https://sea2.discourse-cdn.com/flex002/user_avatar/internals.rust-lang.org/massou/32/10103_2.png) [@Massou](https://internals.rust-lang.org/u/Massou)\
**Post date:** [May 5, 2023, 9:29am UTC](https://internals.rust-lang.org/t/thoughts-on-tuples/18778/5 "2023-05-05T09:29:12Z")

</div>

Indeed, my first post is not a proposal but a list of things I miss and couldn't implement directly. Those 3 things are separate but the combo is something I want to have (if possible ofc).

I can write an RFC Covering tuples patterns/variadic tuples if it does not collude with work already in progress.

---

<div class="post-metadata">

**Author:** ![digama0](https://sea2.discourse-cdn.com/flex002/user_avatar/internals.rust-lang.org/digama0/32/6384_2.png) [@digama0](https://internals.rust-lang.org/u/digama0)\
**Post date:** [May 5, 2023, 2:17pm UTC](https://internals.rust-lang.org/t/thoughts-on-tuples/18778/6 "2023-05-05T14:17:58Z")

</div>

Tuple subslicing is relatively accessible to today's rust, that could be an RFC. The other stuff sounds very far off and related to variadic generics, as mentioned.

... Actually tuple subslicing has a problem, which I'm sure would come up in the RFC: you can't ref-bind a tuple subslice because the fields of a tuple don't have to be stored in order.

---

<div class="post-metadata">

**Author:** ![Massou](https://sea2.discourse-cdn.com/flex002/user_avatar/internals.rust-lang.org/massou/32/10103_2.png) [@Massou](https://internals.rust-lang.org/u/Massou)\
**Post date:** [May 5, 2023, 5:26pm UTC](https://internals.rust-lang.org/t/thoughts-on-tuples/18778/7 "2023-05-05T17:26:41Z")

</div>

Interesting,

> ... Actually tuple subslicing has a problem, which I'm sure would come up in the RFC: you can't ref-bind a tuple subslice because the fields of a tuple don't have to be stored in order.

This seems weird to me since patterns already work on individual fields, but it makes sense depending on how the compiler works internally, could you give me more insight ?

did you mean the following don't work because `b` may be reordered to (3, 2) instead of (2, 3) ?

```rust
let (a, ref mut b @ .., c) = (1, 2, 3, 4);
let (d, e) = b;

```

---

<div class="post-metadata">

**Author:** ![digama0](https://sea2.discourse-cdn.com/flex002/user_avatar/internals.rust-lang.org/digama0/32/6384_2.png) [@digama0](https://internals.rust-lang.org/u/digama0)\
**Post date:** [May 5, 2023, 6:00pm UTC](https://internals.rust-lang.org/t/thoughts-on-tuples/18778/8 "2023-05-05T18:00:43Z")

</div>

It's not that the value of `b` can be `(3, 2)`, that would clearly be bad. But references have to point to a certain location in memory, and if it is a tuple then the layout has to match that of all other tuples with those types since you could call a function expecting a `&(T, U)` and it won't "remember" that this particular `(T, U)` has a weird layout.

To give a more concrete example, consider the type `(u8, u16, u8, u16)`. The compiler is incentivized to lay out this type in memory with the two u8's at the beginning so that the whole struct only uses 6 bytes instead of 8. But then if I match it as `let (_, _, ref mut x @ ..) = (0u8, 0u16, 0u8, 0u16)`, `x` will be of type `&(u8, u16)` but with its fields in the wrong place (since there is a `u16` between the two fields). If I passed it to `fn foo(_: &(u8, u16)) {}` the function `foo` would expect the two fields to be next to each other, which is not the case here.

---

<div class="post-metadata">

**Author:** ![Massou](https://sea2.discourse-cdn.com/flex002/user_avatar/internals.rust-lang.org/massou/32/10103_2.png) [@Massou](https://internals.rust-lang.org/u/Massou)\
**Post date:** [May 5, 2023, 7:03pm UTC](https://internals.rust-lang.org/t/thoughts-on-tuples/18778/9 "2023-05-05T19:03:10Z")

</div>

ok, so if I understand correctly tuple patterns could cause de-optimization of code by forcing a memory layout and/or force the use of multiple pointers and this behavior should be specified by an eventual rfc.

Naively it seem acceptable that

```rust
let (_, _, ref mut a @ ..) : (u8, u16, u8, u16) = ...;

```

would be equivalent to

```rust
let (_, _, ref mut a, ref mut b) = ...;

```

Now I'm curious in which case wasting few bytes might be preferable.

How are the size decided ? is there a pass that is able to determine if a specific instance of a tuple is only present in a stack frame vs stored somewhere like in a collection ?

---

<div class="post-metadata">

**Author:** ![digama0](https://sea2.discourse-cdn.com/flex002/user_avatar/internals.rust-lang.org/digama0/32/6384_2.png) [@digama0](https://internals.rust-lang.org/u/digama0)\
**Post date:** [May 5, 2023, 7:13pm UTC](https://internals.rust-lang.org/t/thoughts-on-tuples/18778/10 "2023-05-05T19:13:11Z")

</div>

> [@Massou](#):
>
> ok, so if I understand correctly tuple patterns could cause de-optimization of code by forcing a memory layout and/or force the use of multiple pointers and this behavior should be specified by an eventual rfc.

No, what I said above means that by-ref tuple patterns are _unimplementable_, this is not about performance. If you by-ref capture something there is the expectation that you have a reference to the original thing, not a copy of it; this is observable in the case of `ref mut` and interior mutability.

> [@Massou](#):
>
> Naively it seem acceptable that
> 
> ```rust
> let (_, _, ref mut a @ ..) : (u8, u16, u8, u16) = ...;
> 
> ```
> 
> would be equivalent to
> 
> ```rust
> let (_, _, ref mut a, ref mut b) = ...;
> 
> ```

It's obviously not equivalent, since in one case you get one binding and in the other case you get two. A `&mut (u8, u16)` is not two pointers, it is one pointer to two things, and those two things have to be situated in a certain way with respect to each other and the pointer.

> [@Massou](#):
>
> How are the size decided ? is there a pass that is able to determine if a specific instance of a tuple is only present in a stack frame vs stored somewhere like in a collection ?

The layout algorithm is deliberately unspecified, but all tuples of the same shape have to have the same layout, so you can't use things like "it is only present in a stack frame" to influence the layout because it has to agree with other runs of the compiler on other crates. You can't layout "a specific instance of a tuple" differently from the tuple itself. (You can optimize tuples away completely with enough analysis, but this is an _optimization_ which means that you can't base a language feature like by-ref tuple pattern bindings on it.)

---

<div class="post-metadata">

**Author:** ![bert](https://avatars.discourse-cdn.com/v4/letter/b/9e8a1a/32.png) [@bert](https://internals.rust-lang.org/u/bert)\
**Post date:** [May 5, 2023, 8:04pm UTC](https://internals.rust-lang.org/t/thoughts-on-tuples/18778/11 "2023-05-05T20:04:47Z")

</div>

If the tuple fields in question are `Copy` then I think Rust should let you pull them out into a new (non-referenced) tuple.

```rust
// At least one of these should be syntactically valid and assign 
// `a = (2, 3)` by copying elements in the RHS into a new tuple
let (_, &a @ .., _) = &(1, 2, 3, 4); 
let (_, a @ *.., _) = &(1, 2, 3, 4);

```

---

<div class="post-metadata">

**Author:** ![VitWW](https://sea2.discourse-cdn.com/flex002/user_avatar/internals.rust-lang.org/vitww/32/10822_2.png) [@VitWW](https://internals.rust-lang.org/u/VitWW)\
**Post date:** [May 5, 2023, 8:40pm UTC](https://internals.rust-lang.org/t/thoughts-on-tuples/18778/12 "2023-05-05T20:40:03Z")

</div>

1. Some simple pattern binding is possible. If you don't make a reference
2. For the rest of yous thoughts "homogeneous tuples" `[( .. T)]` are needed:

```rust
let mut tupl : [(.. i32)] = [(1, 2, 3, 4)];

const while let (head, tail ^^ 1.. ) = tupl {
    if do_something(head) {
        tupl = tail;
    } else {
        tupl = [()];
    }
}
//

trait SomeTrait {}

struct Foo;
impl SomeTrait for Foo {}

struct Bar;
impl SomeTrait for Bar {}

struct Baz;

fn do_something(t: [( ... impl SomeTrait )] ) {}

let fb : [( ... impl SomeTrait )] = [(Foo, Bar)];
do_something(fb); // compiles
let fb : [( ... impl SomeTrait )] = [(Foo, Bar, Baz)]; // compile error

```

1. Unfortunately you need for that `UnSized` Types or their's awful Rust representatives, like a `List` (and homogeneous tuples are Lists)

---

<div class="post-metadata">

**Author:** ![Massou](https://sea2.discourse-cdn.com/flex002/user_avatar/internals.rust-lang.org/massou/32/10103_2.png) [@Massou](https://internals.rust-lang.org/u/Massou)\
**Post date:** [May 5, 2023, 10:13pm UTC](https://internals.rust-lang.org/t/thoughts-on-tuples/18778/13 "2023-05-05T22:13:23Z")

</div>

Thx for your explanatios & patience I think I understand: by ref patterns on tuples should only be allowed if they are either destructured later in the code or used to create a new tuple with refs inside aka: late use as individual members and not as a single tuple. (if the info is accessible by the compiler, otherwise not allowed at all).

Based on my usage of by-ref patterns and the usefulness of pattern in tuples to me it's worth an rfc (except if there are some unresolvable gotchas).

I'm not aware of how much rust users would be interested in this feature.

---

<div class="post-metadata">

**Author:** ![crlf0710](https://sea2.discourse-cdn.com/flex002/user_avatar/internals.rust-lang.org/crlf0710/32/1987_2.png) [@crlf0710](https://internals.rust-lang.org/u/crlf0710)\
**Post date:** [May 6, 2023, 5:52am UTC](https://internals.rust-lang.org/t/thoughts-on-tuples/18778/14 "2023-05-06T05:52:29Z")

</div>

To me these seems like very individual features.

# Tuple slicing

To properly support tuple subslicing from scratch(though i'm not sure if it's worth it at this point), i think it's best to mimick array vs slice's examples, and introduce a tuple slice type.

```rust
fn foo(_: &(|i32, u32|)) {}

let [_, a @ .., _] = &(true, -2, 3, "str");
foo(a);

```

which roughly corresponds to

```rust
fn foo(_: &[i32]) {}

let [_, a @ .., _] = &[1, 2, 3, 4];
foo(a);

```

Here `(|i32, u32|)` is an unsized tuple slice type(syntax same as tuple except adding two bars inside the parenthesis), whose pointee metadata contains information about its origin(element offsets, etc).

# const loops on tuple elements

I haven't thought a lot about the syntax, but to me it's best desugared to something like this:

```rust
trait TupleVisit {
    fn visit_element<T>(&mut self, element: &(|T,|));
}

trait TupleVisitMut {
    fn visit_element_mut<T>(&mut self, element: &mut (|T,|));
}

trait TupleVisitOnce {
    fn visit_element_once<T>(&mut self, element: T);
}

```

This will allow one thing to "receive" the elements in a tuple one-by-one.

# Constraints on tuple members

I think this one needs a more accurate use case... What would one use this for?

---

<div class="post-metadata">

**Author:** ![Massou](https://sea2.discourse-cdn.com/flex002/user_avatar/internals.rust-lang.org/massou/32/10103_2.png) [@Massou](https://internals.rust-lang.org/u/Massou)\
**Post date:** [May 6, 2023, 7:54am UTC](https://internals.rust-lang.org/t/thoughts-on-tuples/18778/15 "2023-05-06T07:54:20Z")

</div>

Some form of `heterogenous tuples` is already possible today, my current workaround is to have an enum with a variant for every different member in the tuple then convert the tuple to an array (ie: [tuplify/hlist.rs at main · cantina-space/tuplify · GitHub](https://github.com/cantina-space/tuplify/blob/main/src/hlist.rs#L1067))

The same trick can work for function parameters by converting a tuple to an array of enum and then taking the array/iterator/slice as parameter, not the best solution but it works. Most of the time I create ad-hoc enums when I need to do this (and hope the compiler is clever enough to optimize but this is not really reliable depending on contexts).

---

<div class="post-metadata">

**Author:** ![Massou](https://sea2.discourse-cdn.com/flex002/user_avatar/internals.rust-lang.org/massou/32/10103_2.png) [@Massou](https://internals.rust-lang.org/u/Massou)\
**Post date:** [May 6, 2023, 8:42am UTC](https://internals.rust-lang.org/t/thoughts-on-tuples/18778/16 "2023-05-06T08:42:04Z")

</div>

> To properly support tuple subslicing from scratch(though i'm not sure if it's worth it at this point), i think it's best to mimick array vs slice's examples, and introduce a tuple slice type.

After looking at my code (probably not representative of all rust users), the places where I want to use tuple tuple subslicing/patterns are almost always in the same function and I rarely need to pass them to function parametes.

for this use case I think that the following would be acceptable without introducing a new user type (not sure if possible with the compiler).

```rust
fn foo(_: (&u32, &i32)) {}

let (_, ref tupl @ ..) = (1, 2, 3, 4);
foo((..tupl)); //ok
let (a, b) = tupl; // ok
foo(tupl); // not ok

```

> I think this one needs a more accurate use case... What would one use this for?

This alone is not very usefull on it's own (without being able to iterate on tuples), the only places where I would use that currently is when I implement some features on tuples/hlists without having to know the common restriction in advance, this would reduce boilerplate.

Think of this kind of code (currently doable but today intermediate traits are needed):

```rust
trait Action {
    fn do_something(&self) -> Result<(), ()>;
}

struct AnyOf<T: TupleOf<Action>>(pub T); // or whatever syntax to have this restriction

impl<T> Action for AnyOf<T> {
    // ...
}

struct OneOf<T: TupleOf<Action>>(pub T);

impl<T> Action for OneOf<T> {
    // ...
}

```

---

<div class="post-metadata">

**Author:** ![crlf0710](https://sea2.discourse-cdn.com/flex002/user_avatar/internals.rust-lang.org/crlf0710/32/1987_2.png) [@crlf0710](https://internals.rust-lang.org/u/crlf0710)\
**Post date:** [May 6, 2023, 8:49am UTC](https://internals.rust-lang.org/t/thoughts-on-tuples/18778/17 "2023-05-06T08:49:20Z")

</div>

> [@Massou](#):
>
> Think of this kind of code (currently doable but today intermediate traits are needed)

Seems coverable with a single pattern(needs some way to specify the `reduce` fn after the automatic `map` part, of course):

```rust
#[derive_structural_propagation]
//^ imaginary attribute that generate all tuple and maybe array impls.
trait Action {
     fn do_something(&self) -> Result<(), ()>;
}

```

Is there more use cases than this?

---

<div class="post-metadata">

**Author:** ![Massou](https://sea2.discourse-cdn.com/flex002/user_avatar/internals.rust-lang.org/massou/32/10103_2.png) [@Massou](https://internals.rust-lang.org/u/Massou)\
**Post date:** [May 6, 2023, 4:28pm UTC](https://internals.rust-lang.org/t/thoughts-on-tuples/18778/18 "2023-05-06T16:28:24Z")

</div>

This is completely doable with proc macro (but maybe overkill depending on use cases), I currently implement this using macros rules.

> Is there more use cases than this?

Not that much, only few similar cases. This is not really useful on it's own except saving ~10 loc per implementation (much more with variadics and loops if they existed).

---

<div class="post-metadata">

**Author:** ![Aloso](https://sea2.discourse-cdn.com/flex002/user_avatar/internals.rust-lang.org/aloso/32/5039_2.png) [@Aloso](https://internals.rust-lang.org/u/Aloso)\
**Post date:** [June 3, 2023, 1:29pm UTC](https://internals.rust-lang.org/t/thoughts-on-tuples/18778/19 "2023-06-03T13:29:26Z")

</div>

> [@crlf0710](#):
>
> To properly support tuple subslicing from scratch(though i'm not sure if it's worth it at this point), i think it's best to mimick array vs slice's examples, and introduce a tuple slice type.

Why not make `ref tuple @ ..` desugar to a normal tuple of references? So

```rust
let (_, ref rest @ .., _) = (1, 3u8, 3, 7);
// rest: (&3u8, &3i32)

```

This seems like the simplest and most consistent solution.

---

<div class="post-metadata">

**Author:** ![Aloso](https://sea2.discourse-cdn.com/flex002/user_avatar/internals.rust-lang.org/aloso/32/5039_2.png) [@Aloso](https://internals.rust-lang.org/u/Aloso)\
**Post date:** [June 3, 2023, 1:32pm UTC](https://internals.rust-lang.org/t/thoughts-on-tuples/18778/20 "2023-06-03T13:32:28Z")

</div>

> [@VitWW](#):
>
> For the rest of yous thoughts "homogeneous tuples" `[( .. T)]` are needed:

Homogeneous tuples would be useless because then they'd be just arrays. Being heterogeneous is the only advantage tuples have over arrays.

It would be nice to have heterogeneous tuples with a _trait bound_ though, and being able to filter/map/fold them using that trait.

[Next page](https://internals.rust-lang.org/t/thoughts-on-tuples/18778.md?page=2)
