Skip to content

Does iter_mut() guarentee stable order if you don't insert/remove elements? #749

Open

Description

@jestarray

https://doc.rust-lang.org/std/collections/struct.HashMap.html#method.iter_mut

An iterator visiting all key-value pairs in arbitrary order, with mutable references to the values. The iterator element type is (&'a K, &'a mut V).

Question on the docs here, if you don't insert/remove elements from the hashmap at all and just do:

hashmap.iter_mut();

hashmap.get_mut() += 1; // updating existing values doesn't mutate the hashmap itself vs insertion/removal

hashmap.iter_mut(); //again a few lines down without mutation

Is iteration guaranteed to be stable or can that change one day? I realize I rely on this order being the same. I'm guessing no since there is no test and doc for it so it should not be relied on?

Activity

  1. clarfonthey commented on Sep 13, 2026

    @clarfonthey
    Contributor

    Yes, this is not a guarantee we make and while I also can't imagine it changing, it's probably best to use indexmap in cases like this.

  2. jestarray commented on Sep 13, 2026

    @jestarray
    Author

    noted, thanks

  3. clarfonthey commented on Sep 13, 2026

    @clarfonthey
    Contributor

    (If you don't mind, going to reopen this to track updating docs.)

  4. jestarray commented on Sep 13, 2026

    @jestarray
    Author

    Np, thanks for specifying it in docs. In the event it does happen, can we have a test and changelog in place to warn users? As of now it's stable though, but since it's not a guarantee on all platforms, it really is hard to say 😅

  5. clarfonthey commented on Sep 13, 2026

    @clarfonthey
    Contributor

    My main thought process is that there may be cases where we might want to enable iterator randomisation somehow, since it's been mentioned a few times before. In those cases, it would likely be enabled via an opt-in feature, and thus you wouldn't be able to reliably ensure it doesn't occur in anything that uses it because of feature unification.

    It's a bit of a stretch, but, a potential reason to not explicitly guarantee the order, and to encourage other crates like indexmap in those cases. And, in general, if you want to do a lot of iterating with stable order, indexmap will give you other benefits too, like stable insertion order.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions