Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Relax constraint in hash_map::EntryRef insertion methods K: From<&Q> to &Q: Into<K> #611

Open
wants to merge 1 commit into
base: master
Choose a base branch
from

Conversation

tomkris
Copy link

@tomkris tomkris commented Mar 9, 2025

Currently EntryRef::or_insert* methods have constraint K: From<&Q> which is required to construct "owned" key from "borrowed" key during insertion operation.

Rust documentation recommends not to use From as trait constraint, and instead prefer to use reversed Into trait constraint:

https://doc.rust-lang.org/std/convert/trait.From.html

Prefer using Into over using From when specifying trait bounds on a generic function. This way, types that directly implement Into can be used as arguments as well.

Changing constraint K: From<&Q> to &Q: Into<K> extends support of insert operation to additional cases where K does not implement trait From<&Q>, but &Q does implement trait Into<K>.

API compatibility: &Q: Into<K> is a strict superset of K: From<&Q> (because of blanket implementation https://doc.rust-lang.org/std/convert/trait.Into.html#impl-Into%3CU%3E-for-T), so this change does not break existing hashbrown API compatibility; all existing code will work with new trait constraints.

…to &Q: Into<K>

Currently `EntryRef::or_insert*` methods have constraint `K: From<&Q>` which is
required to construct "owned" key from "borrowed" key during insertion operation.

Rust documentation recommends not to use `From` as trait constraint, and instead
prefer to use reversed `Into` trait constraint:

https://doc.rust-lang.org/std/convert/trait.From.html

> Prefer using Into over using From when specifying trait bounds on a generic
> function. This way, types that directly implement Into can be used as arguments as well.

Changing constraint `K: From<&Q>` to `&Q: Into<K>` extends support of insert operation
to additional cases where `K` does not implement trait `From<&Q>`, but `&Q` does implement
trait `Into<K>`.

**API compatibility**: `&Q: Into<K>` is a strict superset of `K: From<&Q>` (because of blanket
implementation https://doc.rust-lang.org/std/convert/trait.Into.html#impl-Into%3CU%3E-for-T),
so this change does not break existing hashbrown API compatibility; all existing code will work
with new trait constraints.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

1 participant