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

How do I print variables in Rust and have it show everything about that variable, like Ruby's .inspect?

use std::collections::HashMap;

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

编译失败:

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
  |

有没有办法像这样说:

println!("{}", hash.inspect());

并打印出来:

1) "Daniel" => "798-1364"

您要查找的是 Debug 格式化程序:

use std::collections::HashMap;

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

这应该打印:

{"Daniel": "798-1364"}

另请参阅:

  • What is the difference between println's format styles?

Rust 1.32 引入了 dbg 宏:

use std::collections::HashMap;

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

这将打印:

[src/main.rs:6] hash = {
    "Daniel": "798-1364"
}