skip to content

In Rust, how is the standard vec! macro defined with macro_rules!, and why does vec![value; n] need Clone?

level: juniorimportance: must knowfreq 60%

answer

  1. arms tried top to bottom
  2. empty, repeat, comma list
  3. optional trailing comma matcher
  4. repeat arm calls from_elem

basics

~20 s

vec! is a macro_rules! macro with three arms tried in order: empty, element-semicolon-count, and a comma-separated list of expressions. The repeat arm calls vec::from_elem, which fills the vector by cloning the element, so vec![x; n] needs x: Clone.

solid answer

~40 s

In `alloc`, `vec!` is an exported `macro_rules!` macro with three arms that rustc tries top to bottom, expanding the first that matches. `()` expands to `Vec::new()`. `($elem:expr; $n:expr)` expands to a call to `vec::from_elem($elem, $n)`, whose signature is `from_elem<T: Clone>(elem: T, n: usize)`. `($($x:expr),+ $(,)?)` matches one or more comma-separated expressions with an optional trailing comma and builds the vector from a boxed array of them. Because the repeat form clones one value, `vec![Mutex::new(0); 3]` fails with E0277 (`Mutex` is not `Clone`), and `vec![Rc::new(0); 3]` holds three handles to one allocation. The element expression is evaluated once, even when `n` is 0, and `n` may be a runtime value. It is a macro because a function cannot take a variable number of arguments.

code

rust · 15 lines
rust
use std::rc::Rc;

fn main() {
    let empty: Vec<i32> = vec![];
    let listed = vec![1, 2, 3,]; // list arm; $(,)? takes the trailing comma
    let names = vec![String::from("x"); 3]; // repeat arm, String: Clone
    println!("{empty:?} {listed:?} {names:?}");

    let shared = vec![Rc::new(0); 3];
    println!("strong={}", Rc::strong_count(&shared[0]));

    let mut calls = 0;
    let none: Vec<i32> = vec![{ calls += 1; 7 }; 0];
    println!("none={none:?} calls={calls}");
}

go deeper

for a junior

Know that vec! is a macro_rules! macro, the two call forms, and that the repeat form clones one value. Be ready to say why a function could not take any number of elements.

for a middle

Walk through the three arms and how rustc tries them in order, explain $( ),+ and $(,)? in the list arm, and connect the repeat arm to from_elem's T: Clone bound and the E0277 it produces.

for a senior

Spot the review bugs the expansion explains: shared Rc handles from the repeat form, side effects at a zero count, and a hand-written variadic macro missing $(,)? that rejects trailing commas.

for a principal

Use vec! as the model for a team's own literal macros: a list arm, an optional repeat arm, a trailing comma, and paths through $crate, so internal macros feel like std rather than surprising callers.

## What `vec!` is `vec!` is not a function: it is a **declarative macro**, written with `macro_rules!` in the `alloc` crate and re-exported by `std`. A declarative macro is a list of **rules** (often called arms). Each rule has a **matcher**, a pattern over the tokens the caller wrote between the brackets, and a **transcriber**, the tokens that replace the call when the matcher succeeds. Matching happens during compilation, before type checking, on tokens rather than on values. ## The three arms in the real definition Abridged from `library/alloc/src/macros.rs` in Rust 1.99.1 (the third arm's body uses internal helpers and is summarised in a comment): ```rust macro_rules! vec { () => ( $crate::vec::Vec::new() ); ($elem:expr; $n:expr) => ( $crate::vec::from_elem($elem, $n) ); ($($x:expr),+ $(,)?) => ( // builds a boxed array [$($x),+] and turns it into a Vec ); } ``` The pieces of the matchers: - **`$elem:expr`** binds a **metavariable** named `elem` to one Rust expression; `expr` is the **fragment specifier**. - **`;`** outside any `$` construct is a literal token that must appear in the call. - **`$( ... ),+`** is a **repetition**: the inner pattern one or more times, separated by commas. - **`$(,)?`** is an optional trailing comma: `?` means zero or one occurrence. - **`$crate`** in the transcribers makes the paths resolve to the defining crate wherever the macro is used (the lesson on macro hygiene and scope covers why). ## How rustc picks an arm The Reference states the rule: the expander tries each rule in turn and transcribes the first successful match. 1. `vec![]` has no tokens, so the empty arm `()` matches. 2. `vec![0; 4]` fails the empty arm, then the second arm parses `0` as `$elem`, sees the literal `;`, parses `4` as `$n` and matches. 3. `vec![1, 2, 3]` fails the empty arm; the second arm parses `1` but finds `,` where it needs `;`, so it fails and the third arm matches, binding `$x` three times. 4. `vec![1, 2, 3,]` also reaches the third arm, whose `$(,)?` absorbs the trailing comma. The Rust Book shows a simplified version with a single arm `( $( $x:expr ),* )` that pushes each element. That version has no `$(,)?`, and rustc 1.99.1 rejects `book_vec![1, 2, 3,]` with "unexpected end of macro invocation": after a separator comma it expects another expression. ## Why the repeat form needs `Clone` The second arm hands one evaluated value and a count to `from_elem`, declared `pub fn from_elem<T: Clone>(elem: T, n: usize) -> Vec<T>`. The vector is filled by cloning that value, and the bound is checked like any other call: | Call | Arm | What it requires | |---|---|---| | `vec![]` | empty | an element type rustc can infer | | `vec![x; n]` | repeat | `x: Clone`, `n: usize`, which may be a runtime value | | `vec![a, b, c]` | list | every element of one type; no `Clone` needed | `vec![Mutex::new(0); 3]` therefore fails with **E0277**: the trait `Clone` is not implemented for `std::sync::Mutex<{integer}>`, with a note pointing at the bound on `from_elem`. The list form `vec![Mutex::new(0), Mutex::new(0)]` compiles, because each element is its own expression. ## Consequences people trip over - **Clones share what `Clone` shares.** The `vec!` docs warn that `vec![Rc::new(1); 5]` makes five references to the same boxed integer; `Rc::strong_count` on any slot reads 5. - **The element is evaluated once.** `vec![make(); 3]` calls `make` once and clones the result, unlike the list form, which evaluates each expression. - **A zero count still evaluates the element.** The docs say `vec![expr; 0]` evaluates `expr` and immediately drops it, so side effects still happen. - **The count need not be constant.** An array repeat expression `[x; N]` needs a constant length and, for a length above 1, a `Copy` operand, a const block or a path to a constant item; `vec!` needs only `Clone` and any `usize`. ## Why a macro and not a function Rust functions have a fixed number of parameters, so no function can accept `vec![1, 2, 3]` and `vec![1, 2, 3, 4, 5]` alike. A `macro_rules!` repetition matches any number of expressions and expands to code specialised for that call, which is also why `vec!` can offer two different syntaxes, a list and a repeat, under one name.

  • Why does vec![1, 2, 3,] compile while the Rust Book's simplified vec! rejects it?
    std's list arm is `($($x:expr),+ $(,)?)`, so an optional comma may follow the last expression. The book's single arm `( $( $x:expr ),* )` treats every comma as a separator, so after the final comma it expects another expression and rustc reports "unexpected end of macro invocation". Adding `$(,)?` after the repetition is the usual fix.
  • When would you write vec![a, b, c] instead of vec![x; 3] even though both give three elements?
    When each element must be independent or the type is not `Clone`. The repeat form evaluates `x` once and clones it, so `Rc` handles share one allocation and a `Mutex` will not compile. The list form evaluates each expression separately and only needs the elements to share one type.

  • vec! is a variadic function in the standard library
  • vec![make(); 3] calls make three times
  • vec![Rc::new(0); 3] creates three separate allocations
  • vec![expr; 0] never evaluates expr
  • The count in vec![x; n] must be a compile-time constant