Logo

Programming-Idioms

History of Idiom 8 > diff from v27 to v28

Edit summary for version 28 by :
[Rust] Comment emphasize

Version 27

2016-04-14, 08:22:31

Version 28

2016-04-14, 08:24:16

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
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%