-->

How do I print variables in Rust and have it show

2019-04-06 23:09发布

问题:

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

will not compile with error

the trait bound std::collections::HashMap<&str, &str>: std::fmt::Display is not satisfied

Is there a way to say something like:

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

and have it print out:

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

回答1:

What you're looking for is the Debug formatter:

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

This should print:

{"Daniel": "798-1364"}


回答2:

Rust 1.32 introduced a new macro to save us all:

let mut hash = HashMap::new();
hash.insert("Daniel", "798-1364");

dbg!(hash);  

And this will print:

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