如何在Rust中打印变量并显示该变量的所有信息,例如Ruby的.inspect?

25
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个回答

44

你需要的是Debug格式化程序:

use std::collections::HashMap;

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

这应该打印出:

{"Daniel": "798-1364"}

另请参阅:


2
对于自定义的严格类型,您需要使用 #derive(Debug) 特性进行装饰。http://rustbyexample.com/trait/derive.html - RandomInsano

34

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


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接