Nested Tuple In The Rust Language

Please watch this video before reading the content below.


 

In this article, we will learn about de-structuring of a tuple in the Rust programming language. 

let my_tuple = (9, "nine", 9.0);

A tuple can contain elements of different types, but once created, it can not be changed.

We can access its first element as my_tuple.0 and the second as my_tuple.1 and so on.

Another way is called de-structuring,

let (num, num_str, num_float) = my_tuple;

Now, we can access the first element of my_tuple as num and the second as num_str and so on.

Now, we will consider the situation when one tuple is nested inside the other tuple.

let nested_tuple = (9, ("nine", 9.0));

The first element of the nested_tuple is accessed as usual nested_tuple.0, but the second element is itself a tuple. So, (nested_tuple.1).0 is "nine" and (nested_tuple.1).1 is 9.0.

Now, de-structuring works as follows,

 let (num, (num_str, num_float)) = my_tuple;

One unique characteristics I've noticed is that if  the inner nested tuple contains a single element then it is accessed as if it is not nested.

let nested_tuple = (9, ("nine"), 9.0);

 The above tuple will behave like the my_tuple in the starting.

Happy reading. Keep in touch.

Comments

Popular posts from this blog

Programming Concepts Part I

Rust Hello World Program

Programming Concepts Part II