Rust, Software Development

Rust – Display Contents of Array, Tuple, HashMap and Vector

When using collection types, we sometimes do not want to use loops to display each value. For example, in Rust, we can display the content of an Array, Tuple, HashMap (Map), or Vector without loops using the Debug trait.

Rust Debug Trait

These three compound types, by default, implement the Debug trait. Then, we use the following display formatters with println!  or print! functions to display their contents.

  • {:?}
    • single-line display
  • {:#?}
    • pretty-print alternative

For struct instances, please check out How to Display the Contents of Struct

Rust Codes To Display Content of Array

Consider the following array of string values.

To display the values without loops, we use these codes:

Then, we get the output as follows.

Rust Codes To Display Content of Tuple

Here are sample codes to display the content of a tuple in Rust. Remember, a tuple is like an array, but it can hold values of different types, and it uses parentheses instead of square brackets.

When we run the codes, we get this result:

Rust Codes To Display Content of HashMap (Map)

With HashMap (or Map), we need a little bit more code when creating test data. Creating an instance of HashMap is not enough.

When the codes run, we get the following output.

Rust Codes To Display Content of Vector

Output

Complete Codes

These codes are a bit different as we pass our Vec and HashMap instances into my_tuple. Alternatively, we could use the  vec! macro to initialize a Vector.

Output

At this point, we can see that the codes to display the content of an Array, a HashMap (Map), a Tuple, or a Vector are quite similar. We can attribute this benefit to the use of the Debug trait. Therefore, when we have custom compound types or even struct types, we could use the Debug trait to conveniently display their instances’ content with just one line of code. As a result, our Rust codes become more compact.

We tested the codes using Rust 1.52.1.

Loading

Got comments or suggestions? We disabled the comments on this site to fight off spammers, but you can still contact us via our Facebook page!.


You Might Also Like