Skip to content

Can't overload indexing for arrays #49786

Closed
@tarsa

Description

@tarsa

Following code compiled in Rust 1.24.1, but fails to compile under Rust 1.25.0:

use std::ops;

struct MyIndex(bool);

impl ops::Index<MyIndex> for [String; 2] {
    type Output = String;

    fn index(&self, index: MyIndex) -> &String {
        match index.0 {
            false => &self[0],
            true => &self[1],
        }
    }
}

fn main() {
  let a = [String::from("ala"), String::from("ma kota")];
  println!("{}", a[MyIndex(false)]);
}

Terminal session:

$ rustup toolchain list
stable-x86_64-unknown-linux-gnu
1.24.1-x86_64-unknown-linux-gnu (default)
$ rustup default stable-x86_64-unknown-linux-gnu
info: using existing install for 'stable-x86_64-unknown-linux-gnu'
info: default toolchain set to 'stable-x86_64-unknown-linux-gnu'

  stable-x86_64-unknown-linux-gnu unchanged - rustc 1.25.0 (84203cac6 2018-03-25)

$ rustc aaa.rs
error[E0308]: mismatched types
  --> aaa.rs:10:28
   |
10 |             false => &self[0],
   |                            ^ expected struct `MyIndex`, found integral variable
   |
   = note: expected type `MyIndex`
              found type `{integer}`

error[E0308]: mismatched types
  --> aaa.rs:11:27
   |
11 |             true => &self[1],
   |                           ^ expected struct `MyIndex`, found integral variable
   |
   = note: expected type `MyIndex`
              found type `{integer}`

error: aborting due to 2 previous errors

$ rustup default 1.24.1-x86_64-unknown-linux-gnu
info: using existing install for '1.24.1-x86_64-unknown-linux-gnu'
info: default toolchain set to '1.24.1-x86_64-unknown-linux-gnu'

  1.24.1-x86_64-unknown-linux-gnu unchanged - rustc 1.24.1 (d3ae9a9e0 2018-02-27)

$ rustc aaa.rs
$ ./aaa 
ala

Metadata

Metadata

Assignees

No one assigned

    Labels

    A-inferenceArea: Type inferenceC-bugCategory: This is a bug.P-mediumMedium priorityT-langRelevant to the language team, which will review and decide on the PR/issue.disposition-closeThis PR / issue is in PFCP or FCP with a disposition to close it.finished-final-comment-periodThe final comment period is finished for this PR / Issue.regression-from-stable-to-stablePerformance or correctness regression from one stable version to another.

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions