rust-lang / rust-lang/rust-analyzer

[Feature Request] Code Actions: Generate setters that return `&mut Self`

Open
#17,385 6 comments 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

C-feature
Dominant language
Rust
Stars
16.9k
Forks
2.2k
Avg merge
1d 12h
Merged PRs (30d)
72

Description

Hello,

I think it will be extremely useful to auto-generate setters that return a mutable reference to self.

We could use them to chain together setter operations, and simplify our code.

I specifically use them to construct objects, or to only partially modify objects.

Also, chaining together operations is pretty comfy.

For a struct such as this:

struct Student {
    age: usize,
    books: usize,
}

We would use it to construct objects as:

  let me = *Student::new()
    .set_age(30)
    .set_books(300);

Or only partially modify objects as:

 let me = &mut students[i];
 me.set_age(40);

The current code actions only generate setters that don't return anything.

To make this chaining feature work, the setters obviously need to return a &mut Self. As in,

pub fn set_age(&mut self, age: usize) -> &mut Self {
  self.age = age;
  self
}

I think this feature would be extremely useful.

Thanks!

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

No implementation files or tests are named in the issue. Locate the code-action entry point for generating setters and its existing tests, then verify how generated setters are expected to return a mutable reference and support chaining. Done means the requested setter behavior is implemented with coverage for construction and partial mutation.

Written by the indexing model from the issue text.

Assessment

Tech stack
rust
Domain
developer-experience
Issue type
Feature
Difficulty
4/5
Estimated time
3-5 days
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
35/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.