Skip to content
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 Lint for vec![Rc::new(..); N] #3377

Closed
0e4ef622 opened this issue Oct 29, 2018 · 4 comments
Closed

New Lint for vec![Rc::new(..); N] #3377

0e4ef622 opened this issue Oct 29, 2018 · 4 comments
Labels
A-lint Area: New lints L-correctness Lint: Belongs in the correctness lint group

Comments

@0e4ef622
Copy link

A guy on discord got pretty confused by this.

@flip1995
Copy link
Member

Could you please give a little more information here? What should the Lint warn about or suggest? Maybe a code example would also be helpful.

@0e4ef622
Copy link
Author

0e4ef622 commented Oct 29, 2018

The vec! macro uses Clone, and since Rc's clone doesn't duplicate the underlying data, all the elements of the Vec end up pointing to the same thing. This can cause surprising behavior with interior mutability.

use std::{rc::Rc, cell::Cell};
let v = vec![Rc::new(Cell::new(false)); 3];
v[1].set(true);
println!("{:?}", v); // [true, true, true]

@0e4ef622
Copy link
Author

I'm not sure about the best alternative, resize_with seems like a good option but is currently unstable. Possibly something like,

(0..N).map(|_| Rc::new(..)).collect()

¯\_(ツ)_/¯

@flip1995 flip1995 added A-lint Area: New lints L-correctness Lint: Belongs in the correctness lint group labels Oct 29, 2018
@y21
Copy link
Member

y21 commented Jun 16, 2023

This lint exists today. Output for the code above:

warning: initializing a reference-counted pointer in `vec![elem; len]`
 --> src/main.rs:4:13
  |
4 |     let v = vec![Rc::new(Cell::new(false)); 3];
  |             ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  |
  = note: each element will point to the same `Rc` instance
  = help: for further information visit https://rust-lang.github.io/rust-clippy/master/index.html#rc_clone_in_vec_init
  = note: `#[warn(clippy::rc_clone_in_vec_init)]` on by default

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
A-lint Area: New lints L-correctness Lint: Belongs in the correctness lint group
Projects
None yet
Development

No branches or pull requests

3 participants