宏
宏在编译过程中会扩展为 Rust 代码,并且可以接受可变数量的参数。它们以 !
结尾来进行区分。Rust 标准库包含各种有用的宏。
println!(format, ..)
prints a line to standard output, applying formatting described instd::fmt
.format!(format, ..)
的用法与println!
类似,但它以字符串形式返回结果。dbg!(expression)
会记录表达式的值并返回该值。todo!()
用于标记尚未实现的代码段。如果执行该代码段,则会触发 panic。
fn factorial(n: u32) -> u32 { let mut product = 1; for i in 1..=n { product *= dbg!(i); } product } fn fizzbuzz(n: u32) -> u32 { todo!() } fn main() { let n = 4; println!("{n}! = {}", factorial(n)); }
This slide should take about 2 minutes.
这一节的要点是介绍这些常见的便捷功能以及如何使用它们。而为何将它们定义为宏以及它们可以扩展为什么内容,并不是特别关键。
本课程不会介绍如何定义宏,但在后续部分会介绍派生宏的用法。
More To Explore
There are a number of other useful macros provided by the standard library. Some other examples you can share with students if they want to know more:
assert!
and related macros can be used to add assertions to your code. These are used heavily in writing tests.unreachable!
is used to mark a branch of control flow that should never be hit.eprintln!
allows you to print to stderr.