How to Print Array and Vector data to console in Rust?

This tutorial demonstrates how to print array and vector data to the console in Rust.

In Rust,{} is typically used with the Display trait to print normal strings. However, the Display trait is not implemented for arrays and vectors.

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)

The {} placeholder works only with strings in the println macro. So, how do you print arrays or vectors to the console?

You can use {:?} or {vector or array:?} to print data to the console whose data type implements the 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"]

How to Print 2D Vector in Rust?

You can create a 2D vector and iterate over it using iter() and then print each nested vector element using the Debug trait.

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

This prints each nested vector element.