Skip to content

Cannot state a infered lifetime in a closure #38081

@nikonthethird

Description

@nikonthethird

How is it possible to explicitly state the type of the variable x inside the closure:

#[allow(unused_variables)]
fn main() {

    let slice1: &[i32] = &[1, 2, 3, 4, 5][..];
    
    // This works.
    let slice2 = (|x| x)(slice1);
    
    // This does not.
    //let slice3 = (|x: &[i32]| x)(slice1);
}

My expectation is that the commented line should work, as it merely adds a type annotation. However, the compiler displays the following:

rustc 1.13.0 (2c6933acc 2016-11-07)
error[E0495]: cannot infer an appropriate lifetime due to conflicting requirements
 --> <anon>:9:31
  |
9 |     let slice3 = (|x: &[i32]| x)(slice1);
  |                               ^
  |
note: first, the lifetime cannot outlive the anonymous lifetime #1 defined on the block at 9:30...
 --> <anon>:9:31
  |
9 |     let slice3 = (|x: &[i32]| x)(slice1);
  |                               ^
note: ...so that expression is assignable (expected &[i32], found &[i32])
 --> <anon>:9:31
  |
9 |     let slice3 = (|x: &[i32]| x)(slice1);
  |                               ^
note: but, the lifetime must be valid for the call at 9:17...
 --> <anon>:9:18
  |
9 |     let slice3 = (|x: &[i32]| x)(slice1);
  |                  ^^^^^^^^^^^^^^^^^^^^^^^
note: ...so type `extern "rust-call" fn(&[closure@<anon>:9:18: 9:33], (&[i32],)) -> &[i32] {<[closure@<anon>:9:18: 9:33] as std::ops::Fn<(&[i32],)>>::call}` of expression is valid during the expression
 --> <anon>:9:18
  |
9 |     let slice3 = (|x: &[i32]| x)(slice1);
  |                  ^^^^^^^^^^^^^^^^^^^^^^^

error: aborting due to previous error

It this not possible?

Link to Rust Playground: https://is.gd/KYIYfk

Metadata

Metadata

Assignees

No one assigned

    Labels

    A-closuresArea: Closures (`|…| { … }`)A-lifetimesArea: Lifetimes / regions

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions