Same deterministic code on same platform produces different outputs on different runs

Hi.
Please try the following code on the playground and hit "run" successively.
In stdout you'll get rstu some times, and xyzu some other times.
I expected it to return rstu every time.
This is concerning. Any advice and explanations are appreciated. Thank you.

use std::collections::HashMap;
fn main() {
    let mut hm:HashMap<&str,Vec<&str>> = HashMap::new();
    hm.insert("a",vec!["r","s","t"]);
    hm.insert("b",vec!["x","y","z"]);
    let mut hm_iter = hm.into_iter();
    let entry1:(&str,Vec<&str>) = hm_iter.next().unwrap(); 
    let entry2:(&str,Vec<&str>) = hm_iter.next().unwrap(); 
    let mut vec_entry1 = entry1.1;
    vec_entry1.push("u");
    for e in vec_entry1 {println!("{e}");}
}

(Playground)

The code is not deterministic. Every time you create a HashMap, it gets a new randomly-chosen hash function and therefore a random ordering of elements.

6 Likes

HashMap is randomly seeded.

Perhaps you want a hash map with a stable algorithm, or that can be explicitly seeded. rustc uses one (but I don't know how suitable it is for general use).

2 Likes

I think you can use the std hashmap and override the hasher.

1 Like

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.