Skip to content

Commit 4fceedb

Browse files
authored
Rollup merge of rust-lang#79918 - woodruffw-forks:ww/doc-initializer-side-effects, r=dtolnay
doc(array,vec): add notes about side effects when empty-initializing Copying some context from a conversation in the Rust discord: * Both `vec![T; 0]` and `[T; 0]` are syntactically valid, and produce empty containers of their respective types * Both *also* have side effects: ```rust fn side_effect() -> String { println!("side effect!"); "foo".into() } fn main() { println!("before!"); let x = vec![side_effect(); 0]; let y = [side_effect(); 0]; println!("{:?}, {:?}", x, y); } ``` produces: ``` before! side effect! side effect! [], [] ``` This PR just adds two small notes to each's documentation, warning users that side effects can occur. I've also submitted a clippy proposal: rust-lang/rust-clippy#6439
2 parents 02e468e + d986924 commit 4fceedb

File tree

2 files changed

+8
-0
lines changed

2 files changed

+8
-0
lines changed

Diff for: library/alloc/src/macros.rs

+4
Original file line numberDiff line numberDiff line change
@@ -29,6 +29,10 @@
2929
/// to the same boxed integer value, not five references pointing to independently
3030
/// boxed integers.
3131
///
32+
/// Also, note that `vec![expr; 0]` is allowed, and produces an empty vector.
33+
/// This will still evaluate `expr`, however, and immediately drop the resulting value, so
34+
/// be mindful of side effects.
35+
///
3236
/// [`Vec`]: crate::vec::Vec
3337
#[cfg(not(test))]
3438
#[macro_export]

Diff for: library/std/src/primitive_docs.rs

+4
Original file line numberDiff line numberDiff line change
@@ -489,6 +489,10 @@ mod prim_pointer {}
489489
/// * A repeat expression `[x; N]`, which produces an array with `N` copies of `x`.
490490
/// The type of `x` must be [`Copy`].
491491
///
492+
/// Note that `[expr; 0]` is allowed, and produces an empty array.
493+
/// This will still evaluate `expr`, however, and immediately drop the resulting value, so
494+
/// be mindful of side effects.
495+
///
492496
/// Arrays of *any* size implement the following traits if the element type allows it:
493497
///
494498
/// - [`Copy`]

0 commit comments

Comments
 (0)