]> git.lizzy.rs Git - rust.git/blob - src/docs/rc_clone_in_vec_init.txt
Auto merge of #9421 - xphoniex:fix-#9420, r=giraffate
[rust.git] / src / docs / rc_clone_in_vec_init.txt
1 ### What it does
2 Checks for reference-counted pointers (`Arc`, `Rc`, `rc::Weak`, and `sync::Weak`)
3 in `vec![elem; len]`
4
5 ### Why is this bad?
6 This will create `elem` once and clone it `len` times - doing so with `Arc`/`Rc`/`Weak`
7 is a bit misleading, as it will create references to the same pointer, rather
8 than different instances.
9
10 ### Example
11 ```
12 let v = vec![std::sync::Arc::new("some data".to_string()); 100];
13 // or
14 let v = vec![std::rc::Rc::new("some data".to_string()); 100];
15 ```
16 Use instead:
17 ```
18 // Initialize each value separately:
19 let mut data = Vec::with_capacity(100);
20 for _ in 0..100 {
21     data.push(std::rc::Rc::new("some data".to_string()));
22 }
23
24 // Or if you want clones of the same reference,
25 // Create the reference beforehand to clarify that
26 // it should be cloned for each value
27 let data = std::rc::Rc::new("some data".to_string());
28 let v = vec![data; 100];
29 ```