Logo

Programming-Idioms

History of Idiom 8 > diff from v5 to v6

Edit summary for version 6 by :

Version 5

2015-08-20, 15:34:27

Version 6

2015-08-20, 18:33:00

Idiom #8 Initialize a new Map (associative array)

Declare a new map object x, and provide some (key, value) pairs as initial content.

Idiom #8 Initialize a new Map (associative array)

Declare a new map object x, and provide some (key, value) pairs as initial content.

Imports
use std::collections::BTreeMap;
Imports
use std::collections::BTreeMap;
Code
let mut _x = BTreeMap::new();
_x.insert("one", 1);
_x.insert("two", 2);
Code
let mut x = BTreeMap::new();
x.insert("one", 1);
x.insert("two", 2);
Comments bubble
Something different than a BTreeMap might be used, depending on the usage.

The function `new` of the type `BTreeMap` returns a usable map.
The map is stored mutable in the variable `x`.

Maps in Rust are generic but the type is determined by the compiler based on the later usage.
A line such as `x.insert(1,"one")` would therefore not compile.
Comments bubble
Something different than a BTreeMap might be used, depending on the usage.

The function `new` of the type `BTreeMap` returns a usable map.
The map is stored mutable in the variable `x`.

Maps in Rust are generic but the type is determined by the compiler based on the later usage.
A line such as `x.insert(1, "one")` would therefore not compile.
Demo URL
https://play.rust-lang.org/?code=use%20std%3A%3Acollections%3A%3ABTreeMap%3B%0A%0Afn%20main()%20%7B%0A%20%20%20%20let%20mut%20x%20%3D%20BTreeMap%3A%3Anew()%3B%0A%20%20%20%20x.insert(%22one%22%2C%201)%3B%0A%20%20%20%20x.insert(%22two%22%2C%202)%3B%0A%20%20%20%20%0A%20%20%20%20println!(%22%7B%3A%3F%7D%22%2C%20x)%3B%0A%7D%0A&version=stable