What alloc_error_handler does
alloc_error_handler is an attribute macro exposed by the std::prelude::v1 module of the Rust standard library. It is part of the public, stable API and you can rely on it from any edition of Rust.
#[alloc_error_handler] is an attribute macro that wraps an item (function, struct, module) and rewrites it at compile time. The expansion sees the source token stream and emits new tokens that replace the original. The full canonical path is std::prelude::v1::alloc_error_handler; bring it into scope with use std::prelude::v1::alloc_error_handler; or refer to it by its full path.
When to use it
Invoke alloc_error_handler! when you need its compile-time expansion. Macros can do things plain functions cannot: format-string parsing, custom syntax, code generation. Refer to the std::prelude::v1::alloc_error_handler docs for the exact invocation syntax.
Annotated examples
Invoking the alloc_error_handler! macro
fn demo() {
// Macros are invoked with !, not (). The arguments inside the parens
// (or square brackets, or braces) follow each macro's own syntax —
// refer to the std::prelude::v1::alloc_error_handler reference for examples.
alloc_error_handler!();
}
Macros are evaluated at compile time and can do things ordinary functions cannot — variadic arguments, custom syntax, format-string parsing. The `!` after the name is the language tell that you're calling a macro.
For deeper background, see the canonical Rust patterns reference for the broader context behind this section.
Using alloc_error_handler! inside a larger expression
fn build_message(name: &str, count: u32) -> String {
// Many std macros (format!, write!, vec!, etc.) integrate with format
// strings: capture local bindings with {name} or pass values
// positionally with {}.
format!("hello {name} ({count}x via alloc_error_handler!)")
}
Many std macros — format!, vec!, println!, write!, assert! — are deeply integrated with the rest of the language. Inline-format-string capture (`{name}`) is one of the more recent ergonomic wins.
Common pitfalls
Macros expand to source code at compile time, so error messages can point inside the expansion rather than at the call site — `cargo expand` is invaluable for debugging unexpected behaviour. Macros also can't be passed around like functions; if you need a callable you can store, build a closure instead.
For deeper background, see an in-depth Rust idioms cheat sheet for the broader context behind this section.
Performance & threading notes
Macros expand at compile time and contribute zero runtime overhead beyond the cost of the code they expand to. They can, however, slow down compilation noticeably if used heavily — every macro invocation is parsed and expanded.