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
This commit is contained in:
commit
5d8b2a5bf1
|
@ -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]
|
||||
|
|
|
@ -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`]
|
||||
|
|
Loading…
Reference in a new issue