-
Notifications
You must be signed in to change notification settings - Fork 1.6k
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
New assist: Generate IndexMut
implementation from Index
implementation
#15581
Comments
|
I'd like to have a try @rustbot claim |
from impl<T> ops::Index<Axis> for [T; 3] {
type Output = T;
fn index(&self, index: Axis) -> &Self::Output {
&self[index as usize]
}
} to generate impl<T> ops::IndexMut<Axis> for [T; 3] {
fn index_mut(&mut self, index: Axis) -> &mut Self::Output {
&mut self[index as usize]
}
} this example is simple and easy to achieve, just replace struct Map {
data: HashMap<String, i32>
}
impl Index<String> for Map {
type Output = i32;
fn index(&self, key: String) -> &Self::Output {
self.data.get(&key).unwrap()
}
} there should generate impl IndexMut<String> for Map {
fn index_mut(&mut self, key: String) -> &mut Self::Output {
self.data.get_mut(&key).unwrap()
}
} there problem here is that the impl IndexMut<String> for Map {
fn index_mut(&mut self, key: String) -> &mut Self::Output {
todo!()
}
} |
I think a good compromise would be to keep the But there should definitely be a rewrite rule for |
make a rewrite rule based on rust-analyzer internal api for unpredicable |
feat: add generate_mut_trait_impl assist ![generate_mut_trait_impl](https://github.com/rust-lang/rust-analyzer/assets/71162630/362a5a93-e109-4ffc-996e-9b6e4f54fcfa) Generate proper `index_mut` method body refer to `index` method body may impossible due to the unpredicable case (#15581). Here just leave the `index_mut` method body be same as `index` method body, user can modify it manually to meet their need.
Can this be closed or is there something not yet covered in this issue? |
I think yes, will add other ref/mut trait pair next |
The PR decided to leave some editing to the user as there wasn't a unified way to create IndexMut from Index. If you ask me we can add a simple routine which checks if Index uses |
Given an existing
core::ops::Index
implementation, this assist would generate a copy of it whereIndex
becomesIndexMut
&
in the return value position in the function body (and perhaps other obviously-relevant positions) is replaced with&mut
For an example from the code I'm working on right now,
could be used to generate
with no manual changes instead of 6. There might be other ref/mut trait pairs that could be assisted similarly, too.
The text was updated successfully, but these errors were encountered: