A very simple question: Assume I have a tuple (1, true). How can I get its reverse (true, 1)?
I want a reverse function that can accept any tuple regardless of its size. Is there already such a builtin function? Otherwise how can I write this function or macro?
It's not possible to be generic over tuples of arbitrary sizes. You can create a trait that you implement for tuples up to a limited arity, in the obvious way (eg., (tuple.1, tuple.0) for pairs).
Why do you need this? If you tell us what you are trying to achieve, we can perhaps offer better alternatives.
Rust tuples are not considered to be array-like. They're treated as structs with poorly-named fields 0, 1, etc.
So just like Rust doesn't have a way to swap struct Foo {a: i32, b: bool} to struct Foo {b: bool, a: i32}, it doesn't have such built-in operations on tuples.
You could just make a new tuple by hand. If you swap them a lot, you can make a helper function:
fn rev2<A, B>((a, b): (A, B)) -> (B, A) {
(b, a)
}
Note that you will have to implement it for every tuple length separately, because again tuples are separate types, not arrays.
I wrote crate tuplex to support push() operation on tuples, which is required in my use case. To support yours, a Reverse trait could be implemented by tuples of different lengths, but with the limits of max length, e.g 32.
It is not a serious use case. I was writing a simple program that stores an ordered list of various kinds of objects. I should define a trait and put them in an array of trait objects. But for such simple program I thought a tuple might work. It did work until I wanted to print them in reverse order.