DEV Community

El Bruno for Microsoft Azure

Posted on • Originally published at elbruno.com on

#Rust πŸ¦€ – Working with arrays, vectors and println! macro in Debug mode πŸ›

Hi !

It’s time to learn a little about arrays and vectors. And sure, using println! is a great way to check how this elements works. However, there is a little something extra to learn here.

Let me start with a simple scenario. Defining a vector with weekdays, and print the content. Something like this


    // Declare array with weekdays
    let days = [
        "Sunday",
        "Monday",
        "Tuesday",
        "Wednesday",
        "Thursday",
        "Friday",
        "Saturday",
    ];

    // print days 
    println!("{}", days);

Enter fullscreen mode Exit fullscreen mode

And this is the output, with a super cool error.


error[E0277]: `[&str; 7]` doesn't implement `std::fmt::Display`
  --> src\main.rs:38:20
   |
38 | println!("{}", days);
   | ^^^^ `[&str; 7]` cannot be formatted with the default formatter
   |
   = help: the trait `std::fmt::Display` is not implemented for `[&str; 7]`
   = note: in format strings you may be able to use `{:?}` (or {:#?} for pretty-print) instead

Enter fullscreen mode Exit fullscreen mode

In order to work and print an array (or other complex elements) we may want to use the println! macro in Debug Mode (more information on Debug Mode here). We need to use the β€œ{:?}” marker for debugging purposes.

So, once we give it a try, we have this output.


    Finished dev [unoptimized + debuginfo] target(s) in 0.57s
     Running `target\debug\arr01.exe`
["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"]

Enter fullscreen mode Exit fullscreen mode

And it works ! And hey, we even have a beautified debug option using the β€œ{:#?}” marker. In this scenaro we will have the array printed one line for each array element.

Ouput of the debug and debug beautifier sample to print weekedays with the output ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"]<br>
[<br>
    "Sunday",<br>
    "Monday",<br>
    "Tuesday",<br>
    "Wednesday",<br>
    "Thursday",<br>
    "Friday",<br>
    "Saturday",<br>
]

The full source code for the previous scenario is available here.

More in the official Rust Documentation for Formatted Strings.

Happy coding!

Greetings

El Bruno

More posts in my blog ElBruno.com.


Top comments (0)