Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is tuple formatting limited to 12 items in Rust?

I just started a tutorial in Rust and I can't get my head around the limitation of tuple printing:

fn main() {
    // Tuple definition
    let short = (0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11);
    let long = (0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12);

    println!("{:?}", short); // Works fine
    println!("{:?}", long);  // ({integer}...{integer})` cannot be formatted using `:?` because it doesn't implement `std::fmt::Debug`
}

In my ignorant view the printing could be easily achieved by iterating over the entire tuple — this would allow displaying without size constraint. If the solution would be that simple it would be implemented, what am I missing here?

like image 381
magu_ Avatar asked Aug 14 '18 16:08

magu_


People also ask

Are tuples mutable in Rust?

In Rust, a tuple is immutable, which means we cannot change its elements once it is created.

How do you print a tuple in Rust?

Use the println!( "{:?}", tuple_name) syntax to print values in a tuple.

How are tuples implemented in Rust?

Tuples are constructed using parentheses () , and each tuple itself is a value with type signature (T1, T2, ...) , where T1 , T2 are the types of its members. Functions can use tuples to return multiple values, as tuples can hold any number of values. // The following struct is for the activity.

How do you access tuple elements in Rust?

Tuple values are accessed with dot notation where we separate the tuple name and the value index number with a dot operator. Tuples cannot be iterated over like an array or collection.


1 Answers

Printing tuples is currently implemented using a macro that only works up to 12 elements.

Functionality to statically iterate/manipulate tuples has been proposed, but has been postponed (see e.g. this RFC). There was some concerns about the implementation of these (e.g. you'd expect to be able to get the head & tail of a tuple, but there is actually no guarantee that a tuple will be stored in the same order as you specified, because the compiler is allowed to optimize for space, which means getting the tail wouldn't be a trivial operation).

As for why you need special support for that, consider the following tuple:

let mixed = (42, true, 3.14, "foo");

How you would iterate this tuple, given that all its elements have a different type? This can't simply be done using regular iterators and a for loop. You would need some new type-level syntax, which Rust is currently lacking.

like image 113
mcarton Avatar answered Oct 03 '22 18:10

mcarton