为什么在 Rust 中 println! 和其他宏有感叹号?
大家好!我大概一周前开始学习 Rust,遇到了一个让我有点困惑的问题。为什么在 Rust 中输出到控制台时,我们要写 `println!` 并带上感叹号?我习惯了 Python、Java 和 C++,这些语言中函数调用总是没有感叹号,比如 `print()`、`System.out.println()` 或 `std::cout <<`。
我看了示例——到处都写 `println!("Hello, world!");`。我尝试只写 `println("Hello");`——编译器报错了:
```
error[E0423]: expected function, found macro `println`
--> src/main.rs:2:5
|
2 | println("Hello");
| ^^^^^^^ not a function
```
为什么会这样?这是某种特殊函数吗?还是语言特性?我读到 Rust 中有宏,但不太明白它们和普通函数有什么区别。还有:`format!`、`vec!`——也带感叹号。这些都是宏吗?我什么时候需要使用感叹号,什么时候不需要?
请用简单的话给新手解释一下。