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

Generate new method

Open vanillajonathan opened this issue 5 years ago • 6 comments

When I hover the mouse cursor over a struct or a impl, I want the light bulb to present me with "Create new method".

If I have:

struct Point {
    x: i32,
    y: i32,
}

And hover my mouse cursor over the "Point" (the struct keyword or the struct name), then I would get presented with the light bulb, and if I chose "Create new method", it would turn it into.

struct Point {
    x: i32,
    y: i32,
}

impl Point {
    fn new() -> Point {
        // TODO return a new Point
    }
}

or perhaps even better?

struct Point {
    x: i32,
    y: i32,
}

impl Point {
    fn new(x: i32, y: i32) -> Point {
        Point { x: x, y: y }
    }
}

vanillajonathan avatar Jul 22 '20 08:07 vanillajonathan

rust-analyzer provides this already. @Xanewok @matklad considering the RA plugin is now being merged here, how should we handle cases like this?

flodiebold avatar Jul 22 '20 09:07 flodiebold

I would say closing with "implemented with rust-analyzer backend" is probably the right call.But probably after we conclude the merge

matklad avatar Jul 22 '20 09:07 matklad

rust-analyzer provides this already

How do I access this from vscode though? I'm not getting a light bulb or any other kind of indication that RA can do something special here.

impl<Prov> Pointer<Option<Prov>> {
    fn foo() -> Self {
        Pointer { /* cursor is here */ }
    }
}

The only thing I know to do is delete the line, type Pointe, and then pick Pointer { ... } from the autocompletion. That generates a struct instance with all the field names written out, which is nice.

(Then also a lightbulb shows up, but only with very generic things: "extract into function", "sort methods alphabetically".)

RalfJung avatar Jul 23 '22 12:07 RalfJung

@RalfJung the Generate new assist is only available on the definition of the struct, so you have to go to the definition and press Ctrl+. there.

flodiebold avatar Jul 23 '22 13:07 flodiebold

Ah I see. :)

Is there a list of these magic assists somewhere, and which cursor positions trigger them? They sound really useful, but not very easy to discover.

RalfJung avatar Jul 23 '22 14:07 RalfJung

https://rust-analyzer.github.io/manual.html#assists-code-actions

lnicola avatar Jul 23 '22 14:07 lnicola