alloc/macros.rs
1/// Creates a [`Vec`] containing the arguments.
2///
3/// `vec!` allows `Vec`s to be defined with the same syntax as array expressions.
4/// There are two forms of this macro:
5///
6/// - Create a [`Vec`] containing a given list of elements:
7///
8/// ```
9/// let v = vec![1, 2, 3];
10/// assert_eq!(v[0], 1);
11/// assert_eq!(v[1], 2);
12/// assert_eq!(v[2], 3);
13/// ```
14///
15/// - Create a [`Vec`] from a given element and size:
16///
17/// ```
18/// let v = vec![1; 3];
19/// assert_eq!(v, [1, 1, 1]);
20/// ```
21///
22/// Note that unlike array expressions this syntax supports all elements
23/// which implement [`Clone`] and the number of elements doesn't have to be
24/// a constant.
25///
26/// This will use `clone` to duplicate an expression, so one should be careful
27/// using this with types having a nonstandard `Clone` implementation. For
28/// example, `vec![Rc::new(1); 5]` will create a vector of five references
29/// to the same boxed integer value, not five references pointing to independently
30/// boxed integers.
31///
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///
36/// [`Vec`]: crate::vec::Vec
37#[cfg(not(no_global_oom_handling))]
38#[macro_export]
39#[stable(feature = "rust1", since = "1.0.0")]
40#[rustc_diagnostic_item = "vec_macro"]
41#[allow_internal_unstable(rustc_attrs, liballoc_internals)]
42macro_rules! vec {
43 () => (
44 $crate::vec::Vec::new()
45 );
46 ($elem:expr; $n:expr) => (
47 $crate::vec::from_elem($elem, $n)
48 );
49 ($($x:expr),+ $(,)?) => (
50 // Using `write_box_via_move` produces a dramatic improvement in stack usage for unoptimized
51 // programs using this code path to construct large Vecs. We can't use `write_via_move`
52 // because this entire invocation has to remain a call chain without `let` bindings, or else
53 // inference and temporary lifetimes change and things break (see `vec-macro-rvalue-scope`,
54 // `vec-macro-coercions`, and `autoderef-vec-box-fn-36786` tests).
55 //
56 // `box_assume_init_into_vec_unsafe` isn't actually safe but the way we use it here is. We
57 // can't use an unsafe block as that would also wrap `$x`.
58 $crate::boxed::box_assume_init_into_vec_unsafe(
59 $crate::intrinsics::write_box_via_move($crate::boxed::Box::new_uninit(), [$($x),+])
60 )
61 );
62}
63
64/// Creates a `String` using interpolation of runtime expressions.
65///
66/// The first argument `format!` receives is a format string. This must be a string
67/// literal. The power of the formatting string is in the `{}`s contained.
68/// Additional parameters passed to `format!` replace the `{}`s within the
69/// formatting string in the order given unless named or positional parameters
70/// are used.
71///
72/// See [the formatting syntax documentation in `std::fmt`](../std/fmt/index.html)
73/// for details.
74///
75/// A common use for `format!` is concatenation and interpolation of strings.
76/// The same convention is used with [`print!`] and [`write!`] macros,
77/// depending on the intended destination of the string; all these macros internally use [`format_args!`].
78///
79/// To convert a single value to a string, use the [`to_string`] method. This
80/// will use the [`Display`] formatting trait.
81///
82/// To concatenate literals into a `&'static str`, use the [`concat!`] macro.
83///
84/// [`print!`]: ../std/macro.print.html
85/// [`write!`]: core::write
86/// [`format_args!`]: core::format_args
87/// [`to_string`]: crate::string::ToString
88/// [`Display`]: core::fmt::Display
89/// [`concat!`]: core::concat
90///
91/// # Panics
92///
93/// `format!` panics if a formatting trait implementation returns an error.
94/// This indicates an incorrect implementation
95/// since `fmt::Write for String` never returns an error itself.
96///
97/// # Examples
98///
99/// ```
100/// # #![allow(unused_must_use)]
101/// format!("test"); // => "test"
102/// format!("hello {}", "world!"); // => "hello world!"
103/// format!("x = {}, y = {val}", 10, val = 30); // => "x = 10, y = 30"
104/// let (x, y) = (1, 2);
105/// format!("{x} + {y} = 3"); // => "1 + 2 = 3"
106/// ```
107#[macro_export]
108#[stable(feature = "rust1", since = "1.0.0")]
109#[allow_internal_unstable(hint_must_use, liballoc_internals)]
110#[rustc_diagnostic_item = "format_macro"]
111macro_rules! format {
112 ($($arg:tt)*) => {
113 $crate::__export::must_use({
114 $crate::fmt::format($crate::__export::format_args!($($arg)*))
115 })
116 }
117}