Tuples in Rust!

How do I print out the length of a tuple in Rust?

For example

let tup1 = ("testing", 0, 2);

how would I now find out the length of this tuple?

1 Like
println!("{}", 3);

There's no way to determine how long a tuple is other than already knowing how long it is. You could define and implement a trait for it, but you'd still have to implement it manually for every size of tuple you want to support.

That, or find a crate that's already done this.

3 Likes

It's likely you're trying to use tuples for a something they aren't meant for. Tuples are basically anonymous structs: containing a well-known number and type of values.

Getting the length of a tuple is not a useful operation in most circumstances, since you also can't index them with a variable index at runtime, change the length etc.

This may seem odd coming from e.g. Python, where a tuple is basically "an immutable list", and where people don't much care about what type they're using for a one-off sequence. But the distinction between "homogeneous collection" (list/Vec) and "potentially heterogeneous struct" (tuple) is much stronger in Rust.

6 Likes

But What if I want to print all the elements in the tuple using a for loop, I know I can do this in arrays but what about for tuples, If I wanted all the contents listed out how would I do so?

How would I do this manually then?

You can't iterate over a tuple in a for loop - see this comment from Reddit for why (TL;DR: the loop variable would have to be a different type in every iteration, which doesn't really make sense!)

1 Like

You don't. They don't work like that. Just like you can't iterate over the fields of a struct.

trait StaticLength { fn len() -> usize }
impl StaticLength for () { fn len() -> usize { 0 } }
impl<A> StaticLength for (A,) { fn len() -> usize { 1 } }
impl<A,B> StaticLength for (A,B) { fn len() -> usize { 2 } }
// ... and so on
2 Likes

Just implement Display for particular tuple you want to print out, or if you just want print it for Debug purposes just use {:?} format in println!/format!, which is already implemented for every tuple as long, as Debug is implemented for all its elements.

4 Likes

You probably want statically typed heterogeneous lists (HList) from the frunk crate.

1 Like

highly coupled to OP's other topic: Tuples in for loops

If you want something that can have different lengths meaningfully, use a fixed-sized array ([&str; 3]) or a reference to a dynamic array &[&str]).

Tuples are data structures with a single size known at compile time- this is what allows them to be heterogeneous (have different times). ("testing", 0, 2) is not a "list of things", it is specifically one string, two integers.