Warn about using Arc::new() when using the vec![value; size] macro.
What it does
This lint would warn against using Arc::new in the vec![value; size] macro, because it computes the value once and then clones the value size times instead of generating a new Arc each of the size times.
If the user truly wants a vector of Arcs all pointing to the same arc, then they should make that obvious by constructing the arc before constructing the vector.
Lint Name
No response
Category
No response
Advantage
No response
Drawbacks
No response
Example
#[test]
fn unexpected_vec_macro_behavior() {
let v = vec![Arc::new(Mutex::new(0usize)); 100];
*v[0].lock().unwrap() = 20;
*v[1].lock().unwrap() = 30;
assert_eq!(*v[0].lock().unwrap(), 20);
}
Could be written as:
#[test]
fn vec_behavior_is_more_obvious() {
let cloned_arc = Arc::new(Mutex::new(0usize));
let v = vec![cloned_arc; 100];
*v[0].lock().unwrap() = 20;
*v[1].lock().unwrap() = 30;
assert_eq!(*v[0].lock().unwrap(), 30);
}
@rustbot label +good-first-issue
Hello there! Im interested in contributing to clippy, and this seems like a nice start. A few questions though:
- Is it ok to take over this lint? I'll be progressing quite slowly unfortunately, due to luck of free time..
- If there can be anyone available for questions along the way that'd be delightful, please!
- Regarding the lint itself - isn't it the case for anything that impls
Clone? Although in the case of Arc its even worse than other types, I presume its always readable to extract initialization outside thevec![value;size]macro
@yonip23 Welcome!
- Yep, no rush.
- You can ask on Zulip, either I or someone else will try to answer you within a day or so.
- Yes, but in this case the behavior could be surprising. This should go in the
suspiciouscategory.
Thanks a lot!
I believe this lint could apply equally to Rc as well.
I believe this lint could apply equally to
Rcas well.
The pr is updated to support Rc as well
Thanks for pointing it out 😃
Just wanted to hop on and say thanks to @yonip23... pretty amazing to me that someone picked this up and that it's almost done two weeks later.
@davidbeesley I'm excited myself to contribute to this amazing project! Thanks for the shout-out, appreciate it 🙏