diff options
| author | Guillaume Gomez <guillaume1.gomez@gmail.com> | 2020-12-14 14:43:44 +0100 |
|---|---|---|
| committer | GitHub <noreply@github.com> | 2020-12-14 14:43:44 +0100 |
| commit | 5d8b2a5bf1ab1a762a19964d7a6e54b4c7b65285 (patch) | |
| tree | 716f7ce83946241793086dbfd7c657ec99bf2ac2 | |
| parent | 3c45bff23dfbb13d9d28afe5dba57c028ba156da (diff) | |
| parent | d986924eb13a103fc79c474eded47a663c91bb7f (diff) | |
| download | rust-5d8b2a5bf1ab1a762a19964d7a6e54b4c7b65285.tar.gz rust-5d8b2a5bf1ab1a762a19964d7a6e54b4c7b65285.zip | |
Rollup merge of #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: https://github.com/rust-lang/rust-clippy/issues/6439
| -rw-r--r-- | library/alloc/src/macros.rs | 4 | ||||
| -rw-r--r-- | library/std/src/primitive_docs.rs | 4 |
2 files changed, 8 insertions, 0 deletions
diff --git a/library/alloc/src/macros.rs b/library/alloc/src/macros.rs index a992d768d63..7d4eff6185d 100644 --- a/library/alloc/src/macros.rs +++ b/library/alloc/src/macros.rs @@ -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] diff --git a/library/std/src/primitive_docs.rs b/library/std/src/primitive_docs.rs index 55171ef2292..7aca5451ebc 100644 --- a/library/std/src/primitive_docs.rs +++ b/library/std/src/primitive_docs.rs @@ -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`] |
