THE BEST NEWSLETTER ANYWHERE
Join 6,000 subscribers and get a daily digest of full stack tutorials delivered to your inbox directly.No spam ever. Unsubscribe any time.
This tutorial shows How to print array and vector data to console in Rust.
In Rust, {}
is used display trait to display the normal string.
display trait is not implemented for Array and Vector.
fn main() {
let vector = vec![5; 30];
println!("{}", vector);
}
It throws error[E0277]: Vec<{integer}>
doesn’t implement std::fmt::Display
and Vec<{integer}>
cannot be formatted with the default formatter
error[E0277]: `Vec<{integer}>` doesn't implement `std::fmt::Display`
--> test.rs:3:20
|
3 | println!("{}", v2);
| ^^ `Vec<{integer}>` cannot be formatted with the default formatter
|
= help: the trait `std::fmt::Display` is not implemented for `Vec<{integer}>`
= note: in format strings you may be able to use `{:?}` (or {:#?} for pretty-print) instead
= note: this error originates in the macro `$crate::format_args_nl` (in Nightly builds, run with -Z macro-backtrace for more info)
{}
works only with strings of data in the println
macro.
Then how do you print the array or vector to the console?
{:?}
or {vector or array:?}
is used to print the data to the console whose data type implements Debug trait.
fn main() {
let vector = vec![1, 2, 3, 4, 5]; // vector of integer
let array = ["one", "two", "three", "four", "five"]; // array of strings
println!("{:?}", vector);
println!("{vector:?}");
println!("{:?}", array);
println!("{array:?}");
}
Output:
[1, 2, 3, 4, 5]
[1, 2, 3, 4, 5]
["one", "two", "three", "four", "five"]
["one", "two", "three", "four", "five"]
Created a 2d vector and iterated using iter()
and printed using debug trait for each nested vector element.
Here is a Rust 2d Vector with an example
fn main() {
let mut vector_2d: Vec<Vec<i32>> = Vec::new();
2d_vector = vec![
vec![1,2,3],
vec![4,5,6],
vec![7,8,9]
];
vector_2d.iter().for_each(|it| {
println!("{:#?}", it);
})
}
🧮 Tags
Recent posts
Julia examples - Variable Type Nim example - Convert String to/from the Int How to get length of an array and sequence in Nim? Nim environment variables - read, set, delete, exists, and iterate examples? How to convert from single character to/from string in Nim?Related posts