-
Notifications
You must be signed in to change notification settings - Fork 12.8k
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
indexing is invariant with respect to key #46060
Comments
This should be fixed by rust-lang/rfcs#2147 if that is implemented |
I reassigned this to wg-traits; nowadays we do a lot around the typesystem |
We talked about this in the types triage meeting today. We decided that this would be a nice enhancement, and really only needs someone to put in the time to implement it. But it's not on our roadmap. |
Mentor instructions:This seems pretty easy to do, though it needs some consideration for where to actually place the modifications, some testing, and some research into (and subsequent fixing of) whether this affects other operators such as Anywho, the simple steps are:
I've embedded what I think is an accurate description of the issue here, though you're welcome to not look at it if you want to work out this issue alone. I don't recommend going through the investigation alone, but just in case, I've nested the explanation. Specifically, the way that autoderef works for the index operator differs from the way that method probing and subsequent confirmation works. For method probe, the self ty ("receiver") of a method call always is "generalized" by supertyping it against a fresh inference variable. This means that instead of thinking of 'long lifetime stays in the method call we end up with, and we are required to relate 'short = 'long . So map[&key] turns into something like: <HashMap<&'long String, u32> as Index<_>>::index(&map, &key) . In fact, if you try that on playground, you can see it reproduces the exact same issue.
Interestingly, this is also due to the fact that we're passing &key , and not key into the index's RHS. That means that we end up using this implementation of Borrow , which requires strict type equality between the type and the key.
|
@rustbot claim |
This is now fixed on master, presumably by NLL Stabilization, cc @compiler-errors |
The
[]
operator is treated as invariant with respect to the key type. We should allow subtyping, I think. Consider this example:Indexing is by-value, so really it should be fine to "upcast" the key.
For reference, there are many workarounds. The example shows 2, but another is to "upcast" the map:
The text was updated successfully, but these errors were encountered: