如何打印结构和数组?

How to print structs and arrays?

Go 似乎可以直接打印结构体和数组。

struct MyStruct {
    a: i32,
    b: i32
}

let arr: [i32; 10] = [1; 10];

您想在您的结构上实现 Debug 特性。使用 #[derive(Debug)] 是最简单的解决方案。然后你可以用 {:?}:

打印它
#[derive(Debug)]
struct MyStruct{
    a: i32,
    b: i32
}

fn main() {
    let x = MyStruct{ a: 10, b: 20 };
    println!("{:?}", x);
}

作为, you can use Debug, but you can also use the Display特征。

所有类型都可以派生(自动创建)fmt::Debug 实现作为 #[derive(Debug)],但 fmt::Display 必须手动实现。

您可以创建自定义输出:

struct MyStruct {
    a: i32,
    b: i32
}

impl std::fmt::Display for MyStruct {
    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
        write!(f, "(value a: {}, value b: {})", self.a, self.b)
    }
}

fn main() {
    let test = MyStruct { a: 0, b: 0 };

    println!("Used Display: {}", test);    
}

Shell:

Used Display: (value a: 0, value b: 0)

更多信息,可以查看fmt module documentation.

由于这里没有人明确回答数组,要打印出一个数组,您需要指定 {:?},也用于打印调试输出

let val = 3;
let length = 32; // the maximum that can be printed without error
let array1d = [val; length];
let array2d = [array1d; length]; // or [[3; 32]; 32];
let array3d = [array2d; length]; // or [[[3; 32]; 32]; 32];

但是 length > 32 的数组将退出并出错:

let length = 33;
let array1d = [3; length];
println("{:?}", array1d);

error[E0277]: the trait bound `[{integer}; 33]: std::fmt::Debug` is not satisfied
--> src\main.rs:6:22
|
|     println!("{:?}", array1d);
|                      ^^^^^^^ the trait `std::fmt::Debug` is not implemented for `[{integer}; 33]`

可以使用此答案中的方法打印出更长的数组:

其实{:?}就够了。

let a = [1, 2, 3, 4, 5];
let complete = &a[..];
println! ("{:?}", a);
println! ("{:?}", complete);
#[derive(Debug)]
 struct Rectangle{
       width: u32,
       height: u32,
  }

fn main(){
   let rec = Rectangle{
      width: 50,
      height: 30,
   };

   println!("The rectangle {:?} ", rec);
   println!("The area of the rectangle is {} pixels", 
   area_rectangle(&rec));
}

fn area_rectangle(rectangle: &Rectangle) -> u32{
    rectangle.width * rectangle.height
}