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?
In Rust, a tuple is immutable, which means we cannot change its elements once it is created.
Use the println!( "{:?}", tuple_name) syntax to print values in a tuple.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With