如何在Rust中打印变量并让它显示有关该变量的所有内容,例如Ruby的.inspect?

And*_*row 10 debugging println rust

use std::collections::HashMap;

fn main() {
    let mut hash = HashMap::new();
    hash.insert("Daniel", "798-1364");
    println!("{}", hash);
}
Run Code Online (Sandbox Code Playgroud)

不会编译错误

特征绑定std :: collections :: HashMap <&str,&str>:std :: fmt ::显示不满意

有没有办法说出类似的话:

error[E0277]: `std::collections::HashMap<&str, &str>` doesn't implement `std::fmt::Display`
 --> src/main.rs:6:20
  |
6 |     println!("{}", hash);
  |                    ^^^^ `std::collections::HashMap<&str, &str>` cannot be formatted with the default formatter
  |
Run Code Online (Sandbox Code Playgroud)

打印出来:

println!("{}", hash.inspect());
Run Code Online (Sandbox Code Playgroud)

Nat*_*ara 17

您正在寻找的是Debug格式化程序:

use std::collections::HashMap;

fn main() {
    let mut hash = HashMap::new();
    hash.insert("Daniel", "798-1364");
    println!("{:?}", hash);
}
Run Code Online (Sandbox Code Playgroud)

这应该打印:

{"Daniel": "798-1364"}
Run Code Online (Sandbox Code Playgroud)

  • 对于custom strict a,您需要使用#derive(Debug)特性来装饰它们.http://rustbyexample.com/trait/derive.html (2认同)

hal*_*elf 5

Rust 1.32引入了dbg宏:

use std::collections::HashMap;

fn main() {
    let mut hash = HashMap::new();
    hash.insert("Daniel", "798-1364");
    dbg!(hash);
}
Run Code Online (Sandbox Code Playgroud)

这将打印:

use std::collections::HashMap;

fn main() {
    let mut hash = HashMap::new();
    hash.insert("Daniel", "798-1364");
    dbg!(hash);
}
Run Code Online (Sandbox Code Playgroud)