Skip to content

back-noncompat error about lifetimes #43372

Closed
@donhcd

Description

@donhcd

Probably the easiest way to see this is to run it on playground, but I'll copy the code onto here as well.

static X: usize = 3;

fn x() -> &'static usize {
    &X
}

fn foo(y: Option<&usize>) -> &usize {
    y.unwrap_or_else(x)
}

fn main() {
    foo(None);
}

This code compiles and runs fine on stable, but fails to compile in beta and nightly with

error[E0495]: cannot infer an appropriate lifetime due to conflicting requirements
 --> src/main.rs:8:7
  |
8 |     y.unwrap_or_else(x)
  |       ^^^^^^^^^^^^^^
  |
note: first, the lifetime cannot outlive the anonymous lifetime #1 defined on the function body at 7:1...
 --> src/main.rs:7:1
  |
7 | / fn foo(y: Option<&usize>) -> &usize {
8 | |     y.unwrap_or_else(x)
9 | | }
  | |_^
note: ...so that types are compatible (expected std::option::Option<&usize>, found std::option::Option<&usize>)
 --> src/main.rs:8:7
  |
8 |     y.unwrap_or_else(x)
  |       ^^^^^^^^^^^^^^
  = note: but, the lifetime must be valid for the static lifetime...
note: ...so that types are compatible (expected &'static usize, found &usize)
 --> src/main.rs:8:7
  |
8 |     y.unwrap_or_else(x)
  |       ^^^^^^^^^^^^^^

error: aborting due to previous error

Apologies if this has already been reported - I searched a bit but didn't see anything like it

Metadata

Metadata

Assignees

No one assigned

    Labels

    A-lifetimesArea: Lifetimes / regionsC-bugCategory: This is a bug.P-mediumMedium priorityT-langRelevant to the language team, which will review and decide on the PR/issue.regression-from-stable-to-stablePerformance or correctness regression from one stable version to another.

    Type

    No type

    Projects

    No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions