#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);

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

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"]

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"]
[
    "Sunday",
    "Monday",
    "Tuesday",
    "Wednesday",
    "Thursday",
    "Friday",
    "Saturday",
]

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

/*
Copyright (c) 2023
Author : Bruno Capuano
Create Time : 2023 January
Change Log :
– Demo working with arrays and println! macro
The MIT License (MIT)
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
fn main() {
// Declare array with weekdays
let days = [
"Sunday",
"Monday",
"Tuesday",
"Wednesday",
"Thursday",
"Friday",
"Saturday",
];
// print days triggers an error
// ^^^^ `[&str; 7]` cannot be formatted with the default formatter
// println!("{}", days);
// print days in debug mode
println!("{:?}", days);
// print days in debug mode with a beautifier
println!("{:#?}", days);
// Declare array, initialize all values to 0, length = 5
let bytes = [0; 5];
// print bytes in debug mode
println!("{:?}", bytes);
// print bytes in debug mode with a beautifier
println!("{:#?}", bytes);
}

More in the official Rust Documentation for Formatted Strings.

Happy coding!

Greetings

El Bruno

More posts in my blog ElBruno.com.

More info in https://beacons.ai/elbruno


Leave a comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.