Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save AurevoirXavier/c5b79db2382709ab7df4ffbbfd193ffb to your computer and use it in GitHub Desktop.
Save AurevoirXavier/c5b79db2382709ab7df4ffbbfd193ffb to your computer and use it in GitHub Desktop.
[Rust] Lifetime of Reference in HashMap
struct Cheese<K1, K2, V> {
things: HashMap<K1, V>,
refs: HashMap<K2, &V>
}
@AurevoirXavier
Copy link
Author

AurevoirXavier commented Oct 24, 2019


KrishnaSannasi:

You can't, Rust dislikes self referential types like this, and there is no syntax to safely create them. (Actually, you can make a self referential type with safe Rust, it's just almost useless)

Even if you try and use unsafe, you can't soundly do this because HashMap reallocates on resizes, and this would invalidate all pointers into it.


More detail: https://users.rust-lang.org/t/lifetimes-of-references-in-hashmaps/33942

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