Skip to content

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

@davidbeesley

Description

@davidbeesley

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

Metadata

Metadata

Assignees

No one assigned

    Labels

    A-lintArea: New lintsgood first issueThese issues are a good way to get started with Clippy

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions