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