如何打印结构和数组?

tez*_*tez 35 rust

Go似乎能够直接打印结构和数组.

struct MyStruct {
    a: i32,
    b: i32
}
Run Code Online (Sandbox Code Playgroud)

let arr: [i32; 10] = [1; 10];
Run Code Online (Sandbox Code Playgroud)

mdu*_*dup 54

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

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

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

  • 我们可以对数组使用 Debug 特性吗? (3认同)
  • 也可以使用上面答案中所示的相同特征`#[derive(Debug)]`在调试模式下进行漂亮的打印,同时在`println!`中用`{:#?}`替换`{:?}`。宏。可以在[Rust Book Ch-5](https://doc.rust-lang.org/book/ch05-02-example-structs.html#adding-useful-functionality-with-derived-traits)中找到详细信息 (3认同)

Tob*_* S. 10

如果您希望输出的格式正确并带有缩进,则可以使用{:#?}.

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

fn main() {
    let x = MyStruct{ a: 10, b: 20 };
    println!("{:#?}", x);
}
Run Code Online (Sandbox Code Playgroud)

输出:

MyStruct {
    a: 10,
    b: 20,
}
Run Code Online (Sandbox Code Playgroud)


Ang*_*gel 9

正如mdup所说,你可以使用Debug,但你也可以使用这个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);    
}
Run Code Online (Sandbox Code Playgroud)

贝壳:

Used Display: (value a: 0, value b: 0)
Run Code Online (Sandbox Code Playgroud)

有关更多信息,请查看fmt模块文档.


dta*_*sev 8

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

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];
Run Code Online (Sandbox Code Playgroud)

但是数组 wherelength > 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]`
Run Code Online (Sandbox Code Playgroud)

可以使用以下答案中的方法打印出更长的数组:Implement Debug trait for large array type


小智 5

实际上只是{:?}足够了。

let a = [1, 2, 3, 4, 5];
let complete = &a[..];
println! ("{:?}", a);
println! ("{:?}", complete);
Run Code Online (Sandbox Code Playgroud)

  • 它仅适用于其内部元素实现“Debug”特征的数组。 (4认同)
  • 这对于结构不是正确的。它仅适用于数组。 (2认同)