Skip to content

Can’t declare lifetime for closure that returns a reference #22340

Open
@yonran

Description

@yonran

When you declare closure argument types, there is no syntax to declare a lifetime parameter. And I guess lifetime elision does not apply to closures. Therefore, there seems to be no way to declare the type of a closure that returns a reference.

It compiles if you avoid declaring the type of the closure and depend on type inference. But then you would not be able to assign the closure to a local variable.

fn print_first(list: Vec<String>) {
    let x: &str = list
    .first()
    .map(|s: &String| -> &str &s[])  // ERROR 
    //.map(|s: &String| &s[]) // ERROR
    //.map(|s| -> &str &s[]) // ERROR
    //.map(|s| &s[])  // OK
    .unwrap_or("");
    println!("First element is {}", x);
}

It gives a compiler error and a suggestion that does not make sense.

    src/rusttest.rs:4:29: 4:32 error: cannot infer an appropriate lifetime for lifetime parameter 'a in function call due to conflicting requirements
    src/rusttest.rs:4   .map(|s: &String| -> &str &s[])
                                                   ^~~
    src/rusttest.rs:1:1: 10:2 help: consider using an explicit lifetime parameter as shown: fn print_first<'a>(list: Vec<String>)
    src/rusttest.rs:1 fn print_first(list: Vec<String>) {
    src/rusttest.rs:2   let x: &str = list
    src/rusttest.rs:3   .first()
    src/rusttest.rs:4   .map(|s: &String| -> &str &s[])  // ERROR
    src/rusttest.rs:5   //.map(|s: &String| &s[]) // ERROR
    src/rusttest.rs:6   //.map(|s| -> &str &s[]) // ERROR

This bug is filed after I asked this question on stack overflow. It may be related to Region inference fails for closure parameter #17004.

Metadata

Metadata

Assignees

No one assigned

    Labels

    A-closuresArea: Closures (`|…| { … }`)C-bugCategory: This is a bug.T-compilerRelevant to the compiler 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