Skip to content

Lifetime error when indexing with borrowed index in beta but not in stable #74933

Closed
@rodrimati1992

Description

@rodrimati1992

I tried to compile this code:

use std::mem;
use std::ops::{Index, IndexMut};

pub struct FieldMap;

pub fn insert(this: &mut FieldMap, field: &Field<'_>, value: ()) -> () {
    this[field] = value;
}

pub struct Field<'a> {
    x: &'a (),
}

impl<'a> Index<&'a Field<'a>> for FieldMap {
    type Output = ();

    fn index(&self, _: &'a Field<'a>) -> &() {
        unimplemented!()
    }
}

impl<'a> IndexMut<&'a Field<'a>> for FieldMap {
    fn index_mut(&mut self, _: &'a Field<'a>) -> &mut () {
        unimplemented!()
    }
}

I expected the code to compile

Instead, it failed to compile with this lifetime error:

error[E0623]: lifetime mismatch
 --> src/lib.rs:7:5
  |
6 | pub fn insert(this: &mut FieldMap, field: &Field<'_>, value: ()) -> () {
  |                                           ----------
  |                                           |
  |                                           these two types are declared with different lifetimes...
7 |     this[field] = value;
  |     ^^^^^^^^^^^ ...but data from `field` flows into `field` here

Workarounds

If I change the function in these ways it compiles.

https://play.rust-lang.org/?version=beta&mode=debug&edition=2018&gist=ca6b8a2243d7116cb8180bb4300f6edc

pub fn insert<'a,'b,'c>(this: &'a mut FieldMap, field: &'b Field<'c>, value: ()) -> () {
    this[field as &'b Field<'b>] = value;
}

https://play.rust-lang.org/?version=beta&mode=debug&edition=2018&gist=21326b3dcd6c017d0e644ef7eab89769

pub fn insert<'a,'b,'c>(this: &'a mut FieldMap, field: &'b Field<'c>, value: ()) -> () {
    *this.index_mut(field) = value;
}

Meta

This compiles successfully on Stable Rust 1.45.0 back to 1.26.0 (when '_ lifetimes were stabilized)

This fails to compile on these versions(haven't tried previous ones in the same channels):

  • 1.46.0-beta.2 (2020-07-23 6f95990)
  • 1.47.0-nightly (2020-07-28 a7eff79)

This issue has been assigned to @nbdd0121 via this comment.

Metadata

Metadata

Assignees

Labels

C-bugCategory: This is a bug.P-criticalCritical priorityT-compilerRelevant to the compiler team, which will review and decide on the PR/issue.regression-from-stable-to-betaPerformance or correctness regression from stable to beta.

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions