How do I print variables in Rust and have it show

2019-04-06 22:46发布

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"

2条回答
Fickle 薄情
2楼-- · 2019-04-06 23:22

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"}
查看更多
成全新的幸福
3楼-- · 2019-04-06 23:31

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

查看更多
登录 后发表回答