本文将阐释 Rust 中函数与类函数宏的区别,例如为何 msg! 后带有感叹号 !。我们将深入探讨这种语法的意义及其应用。
本文将阐释 Rust 中函数与类函数宏的区别,例如为何 msg! 后带有感叹号 !。我们将深入探讨这种语法的意义及其应用。
Rust 作为强类型语言,不支持函数接受任意数量的参数。例如,Python 的 print 函数可以灵活处理:
print(1) # 单个参数
print(1, 2) # 两个参数
print(1, 2, 3) # 三个参数
在 Rust 中,带有 ! 的语法(如 println! 或 msg!)表示这是一个类函数宏,而非普通函数。
Rust 中用于输出的普通函数是 std::io::stdout().write,它只接受单一字节切片参数:
use std::io::Write;
fn main() {
std::io::stdout().write(b"Hello, world!\n").unwrap(); // 输出字节切片
}
注意,write 是函数,没有 !。若尝试像 Python 那样传入多个参数,会编译失败:
use std::io::Write;
fn main() {
std::io::stdout().write(b"1\n").unwrap();
// std::io::stdout().write(b"1", b"2\n").unwrap(); // 编译失败:参数数量不匹配
}
若想支持任意参数数量,一个低效的办法是为每种参数个数编写特定函数:
use std::io::Write;
fn print1(arg1: &[u8]) { // 输出单个参数
std::io::stdout().write(arg1).unwrap();
}
fn print2(arg1: &[u8], arg2: &[u8]) { // 输出两个参数
let combined = [arg1, b" ", arg2].concat();
std::io::stdout().write(&combined).unwr...
如果觉得我的文章对您有用,请随意打赏。你的支持将鼓励我继续创作!