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

Warn about using Arc::new() when using the vec![value; size] macro.

Open davidbeesley opened this issue 4 years ago • 8 comments

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);
    }

davidbeesley avatar Apr 18 '22 17:04 davidbeesley

@rustbot label +good-first-issue

Serial-ATA avatar Apr 24 '22 15:04 Serial-ATA

Hello there! Im interested in contributing to clippy, and this seems like a nice start. A few questions though:

  1. Is it ok to take over this lint? I'll be progressing quite slowly unfortunately, due to luck of free time..
  2. If there can be anyone available for questions along the way that'd be delightful, please!
  3. 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 the vec![value;size] macro

yonip23 avatar Apr 29 '22 21:04 yonip23

@yonip23 Welcome!

  1. Yep, no rush.
  2. You can ask on Zulip, either I or someone else will try to answer you within a day or so.
  3. Yes, but in this case the behavior could be surprising. This should go in the suspicious category.

Serial-ATA avatar Apr 30 '22 00:04 Serial-ATA

Thanks a lot!

yonip23 avatar Apr 30 '22 01:04 yonip23

I believe this lint could apply equally to Rc as well.

infmagic2047 avatar May 02 '22 06:05 infmagic2047

I believe this lint could apply equally to Rc as well.

The pr is updated to support Rc as well Thanks for pointing it out 😃

yonip23 avatar May 04 '22 12:05 yonip23

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 avatar May 05 '22 16:05 davidbeesley

@davidbeesley I'm excited myself to contribute to this amazing project! Thanks for the shout-out, appreciate it 🙏

yonip23 avatar May 05 '22 17:05 yonip23