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

时间:2016-08-19 12:59:06

标签: debugging rust println

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"

2 个答案:

答案 0 :(得分:17)

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

use std::collections::HashMap;

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

这应该打印:

{"Daniel": "798-1364"}

另见:

答案 1 :(得分:5)

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"
}