Skip to content

indexing is invariant with respect to key #46060

@nikomatsakis

Description

@nikomatsakis

The [] operator is treated as invariant with respect to the key type. We should allow subtyping, I think. Consider this example:

#![allow(warnings)]

use std::collections::HashMap;
use std::ops::Index;

fn test<'long, 'short>(map: HashMap<&'long String, u32>, key: &'short String) -> u32 {
    // works: 
    // *map.get(&key).unwrap()
    
    // works:
    // *Index::index(&map, &key)
    
    // does not work, but should:
    map[&key]
}

fn main() {}

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:

{ let map: &HashMap<&'short String, u32> = &map; map[&key]; }

Metadata

Metadata

Assignees

Labels

A-type-systemArea: Type systemC-enhancementCategory: An issue proposing an enhancement or a PR with one.E-mediumCall for participation: Medium difficulty. Experience needed to fix: Intermediate.E-mentorCall for participation: This issue has a mentor. Use #t-compiler/help on Zulip for discussion.S-types-deferredStatus: Identified as a valid potential future enhancement that is not currently being worked onT-compilerRelevant to the compiler team, which will review and decide on the PR/issue.T-typesRelevant to the types team, which will review and decide on the PR/issue.

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions