Skip to content

Extract type as type alias produces invalid code with trait object lifetime inference #20107

Open
@ChrisJefferson

Description

@ChrisJefferson

rust-analyzer version: (eg. output of "rust-analyzer: Show RA Version" command, accessible in VSCode via Ctrl/⌘+Shift+P)

rust-analyzer version: 0.3.2509-standalone [/home/caj/.vscode-server/extensions/rust-lang.rust-analyzer-0.3.2509-linux-x64/server/rust-analyzer]

rustc version: (eg. output of rustc -V)

rustc 1.87.0 (17067e9ac 2025-05-09)

editor or extension: (eg. VSCode, Vim, Emacs, etc. For VSCode users, specify your extension version; for users of other editors, provide the distribution if applicable)

VSCode

Consider the following code.

fn main() {
    let step = 3;
    let funcs: Box<dyn Fn(i64) -> i64> = Box::new(|i| i + step);

    println!("Hello, world! {}", funcs(2));
}

Select the type of 'funcs' and select 'Extract type as type alias'. This produces:

type Type = Box<dyn Fn(i64) -> i64>;

fn main() {
    let step = 3;
    let funcs: Type = Box::new(|i| i + step);

    println!("Hello, world! {}", funcs(2));
}

Which doesn't compile with error:

error[E0597]: `step` does not live long enough
 --> src/main.rs:5:40
  |
4 |     let step = 3;
  |         ---- binding `step` declared here
5 |     let funcs: Type = Box::new(|i| i + step);
  |                ----            ---     ^^^^ borrowed value does not live long enough
  |                |               |
  |                |               value captured here
  |                type annotation requires that `step` is borrowed for `'static`
...
8 | }
  | - `step` dropped here while still borrowed

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions