如何在Rust中打印数组和矢量数据到控制台?

1,251 阅读1分钟

本教程展示了如何在Rust中打印数组和向量数据到控制台。

在Rust中,{} ,使用display trait来显示正常的字符串。display trait对于数组和向量没有实现。

fn main() {
    let vector = vec![5; 30];
    println!("{}", vector);
}

它抛出了错误[E0277]:Vec<{integer}> 没有实现std::fmt::DisplayVec<{integer}> 不能用默认格式化器进行格式化

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)

{} 只对 宏中的数据字符串起作用println

那么你如何将数组或向量打印到控制台?

在Rust中打印向量到控制台

{:?} ,用于将数据类型实现了Debug特性的数据打印到控制台。

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:?}");

}

输出

[1, 2, 3, 4, 5]
[1, 2, 3, 4, 5]
["one", "two", "three", "four", "five"]
["one", "two", "three", "four", "five"]

如何在Rust中打印2d向量?

创建了一个2d向量,并使用iter() 迭代,对每个嵌套的向量元素使用debug trait进行打印。

下面是一个Rust 2d Vector的例子

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