Skip to content

Commit

Permalink
Rollup merge of #79918 - woodruffw-forks:ww/doc-initializer-side-effe…
Browse files Browse the repository at this point in the history
…cts, 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
  • Loading branch information
GuillaumeGomez committed Dec 14, 2020
2 parents 3c45bff + d986924 commit 5d8b2a5
Show file tree
Hide file tree
Showing 2 changed files with 8 additions and 0 deletions.
4 changes: 4 additions & 0 deletions library/alloc/src/macros.rs
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,10 @@
/// to the same boxed integer value, not five references pointing to independently
/// boxed integers.
///
/// Also, note that `vec![expr; 0]` is allowed, and produces an empty vector.
/// This will still evaluate `expr`, however, and immediately drop the resulting value, so
/// be mindful of side effects.
///
/// [`Vec`]: crate::vec::Vec
#[cfg(not(test))]
#[macro_export]
Expand Down
4 changes: 4 additions & 0 deletions library/std/src/primitive_docs.rs
Original file line number Diff line number Diff line change
Expand Up @@ -489,6 +489,10 @@ mod prim_pointer {}
/// * A repeat expression `[x; N]`, which produces an array with `N` copies of `x`.
/// The type of `x` must be [`Copy`].
///
/// Note that `[expr; 0]` is allowed, and produces an empty array.
/// This will still evaluate `expr`, however, and immediately drop the resulting value, so
/// be mindful of side effects.
///
/// Arrays of *any* size implement the following traits if the element type allows it:
///
/// - [`Copy`]
Expand Down

0 comments on commit 5d8b2a5

Please sign in to comment.