Rust-clippy: New Lint for `vec![Rc::new(..); N]`

Created on 29 Oct 2018  Â·  3Comments  Â·  Source: rust-lang/rust-clippy


A guy on discord got pretty confused by this.

A-correctness L-lint

Most helpful comment

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]

All 3 comments

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.

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]

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()

¯\_(ツ)_/¯

Was this page helpful?
0 / 5 - 0 ratings

Related issues

Robbepop picture Robbepop  Â·  3Comments

taiki-e picture taiki-e  Â·  3Comments

phansch picture phansch  Â·  3Comments

f-fr picture f-fr  Â·  3Comments

matthiaskrgr picture matthiaskrgr  Â·  3Comments