Question about HashSet


#1

Hello,

Rust beginner here.
Sorry if my question had given before.

Was playing around with HashSet and made simple demo, but I don’t understand the work flow.
I am iterating over HashSet items and printing them one by one. But, the order seems incorrect.

Here is my code snippet.

use std::collections::HashSet;


fn main() {

    let mut books = HashSet::new();

    books.insert("This is my first book");
    books.insert("This is my second book");
    books.insert("This is my third book");
    books.insert("This is my fourth book");

    for book in books {
        println!("{}", book);
    }
}

And, this is the output.

$ cargo run
   Compiling myrustprogram v0.1.0 (file:///Users/sardor/Projects/myrustprogram)
    Finished debug [unoptimized + debuginfo] target(s) in 0.80 secs
     Running `target/debug/myrustprogram`
This is my first book
This is my fourth book
This is my second book
This is my third book

PS: I came from Python. Simpler explanation would be appreciated.

Edit: updated format.

Thanks in advance,
Sardor


#2

HashSet does not preserver order, so this behavior is expected. Actually it works in the same way as Python’s set type:

>>> s = set()
>>> s.add("abc")
>>> s.add("abcde")
>>> s.add(2)
>>> for i in s:
...  print(i)
... 
abc
2
abcde

If you need to preserver order try to use Vec instead.


#3

Iterating over a set in Rust does not have a guaranteed order. Consider using Vec or linked-hash-map with values set to ().


#4

Thank you all.