매크로의 역할

Rust supports macros, which allow for language extensions that go beyond what functions can achieve. For instance, the assert_eq! macro, commonly used in testing, provides more than a function can. When an assertion fails, the macro generates an error message that includes the file name and line number, something that functions cannot do. Macros work differently, as they are expanded during compilation, replacing the macro call with Rust code.

Macros act like shorthand. During compilation, each macro call is expanded into Rust code before types are checked or machine code is generated. For instance, the assert_eq! macro expands into a match expression, and if the assertion fails, it triggers a panic! macro to generate a failure message at runtime. This is different from C++ macros, which are prone to errors. Rust macros are safer, use pattern matching, and are easier to maintain.

이 장에서는 ..

In this chapter, we’ll explore how to write macros using simple examples and walk through the design of a more advanced macro that embeds JSON literals into programs. Macros in Rust are defined using macro_rules!, which operates entirely through pattern matching. The assert_eq! macro, for example, can use different delimiters like parentheses, square brackets, or curly braces without affecting the functionality.

이 장에서는 간단한 예제를 통해 매크로 작성법을 배우고, JSON 리터럴을 프로그램에 직접 삽입하는 고급 매크로의 설계 과정을 살펴본다. 러스트에서 매크로는 macro_rules!를 사용하여 정의되며, 이는 전적으로 패턴 매칭을 통해 작동한다. assert_eq! 매크로는 괄호, 대괄호, 중괄호 등 다양한 구분자를 사용할 수 있으며, 기능에 아무런 영향을 미치지 않는다.

매크로의 기초

Macro Basics

스크린샷 2024-10-12 오후 6.40.36.png

macro_rules! is the main way to define macros in Rust. Note that there is no ! after assert_eq in this macro definition: the ! is only included when calling a macro, not when defining it.