25
use std::collections::HashMap;

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

will fail to compile:

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
  |

Is there a way to say something like:

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

and have it print out:

1) "Daniel" => "798-1364"
Shepmaster
  • 388,571
  • 95
  • 1,107
  • 1,366
Andrew Arrow
  • 4,248
  • 9
  • 53
  • 80

2 Answers2

43

What you're looking for is the Debug formatter:

use std::collections::HashMap;

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

This should print:

{"Daniel": "798-1364"}

See also:

Shepmaster
  • 388,571
  • 95
  • 1,107
  • 1,366
Lily Mara
  • 3,859
  • 4
  • 29
  • 48
  • 2
    For custom strict a, you'll need to decorate them with the #derive(Debug) trait. http://rustbyexample.com/trait/derive.html – RandomInsano Aug 20 '16 at 13:05
34

Rust 1.32 introduced the dbg macro:

use std::collections::HashMap;

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

This will print:

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

Shepmaster
  • 388,571
  • 95
  • 1,107
  • 1,366
halfelf
  • 9,737
  • 13
  • 54
  • 63