rust-analyzer icon indicating copy to clipboard operation
rust-analyzer copied to clipboard

New assist: change multiple `let` assignments of same variable to a `let` block

Open kerhong opened this issue 3 years ago • 3 comments

I'd like to propose an assist that converts a common pattter of variable initialization by multiple let assignments of same variable (not sure if the pattern has a name) into a let x = {...}; block. I think it often assists with readability, especially if the reassignments are more complex.

This:

let is_even = "123";
let is_even: u32 = is_even.parse()?;
let is_even = is_even % 2 == 0;

into this:

let is_even = {
    let is_even = "123";
    let is_even: u32 = is_even.parse()?;
    is_even % 2 == 0
};

and back.

kerhong avatar Oct 03 '23 00:10 kerhong

A more general assist could be "Extract to a block" which will convert this code:

let a = foo();
bar();
let b = baz();

into:

let b = {
    let a = foo();
    bar();
    baz()
};

hkalbasi avatar Oct 03 '23 07:10 hkalbasi

A more general assist could be "Extract to a block"

I imagine this is much more complex? Need to either verify that a is not accessed below the block or risk breaking the original code (where a was still alive after let b).

What's the policy on assists breaking code?

kerhong avatar Oct 03 '23 13:10 kerhong

The "Extract to function" assist can handle this case, so I think "Extract to block" could too (probably by reusing that code).

hkalbasi avatar Oct 03 '23 14:10 hkalbasi