由于不支持默认参数,您可以使用 Option<T> 获得类似的行为
fn add(a: Option<i32>, b: Option<i32>) -> i32 {
a.unwrap_or(1) + b.unwrap_or(2)
}
这实现了将默认值和函数只编码一次(而不是在每次调用中)的目标,但当然要输入更多内容。函数调用看起来像add(None, None),你可能喜欢也可能不喜欢,这取决于你的观点。
如果您看到在参数列表中没有输入任何内容,因为编码员可能会忘记做出选择,那么这里最大的优势在于明确性;调用者明确表示他们想使用您的默认值,如果他们什么都不放,将会得到编译错误。把它想象成输入add(DefaultValue, DefaultValue)。
你也可以使用宏:
fn add(a: i32, b: i32) -> i32 {
a + b
}
macro_rules! add {
($a: expr) => {
add($a, 2)
};
() => {
add(1, 2)
};
}
assert_eq!(add!(), 3);
assert_eq!(add!(4), 6);
两种解决方案的最大区别在于,使用“Option”-al 参数时,写 add(None, Some(4)) 完全有效,但使用宏模式匹配则不能(这类似于 Python 的默认参数规则)。
您还可以使用“参数”结构和 From/Into 特征:
pub struct FooArgs {
a: f64,
b: i32,
}
impl Default for FooArgs {
fn default() -> Self {
FooArgs { a: 1.0, b: 1 }
}
}
impl From<()> for FooArgs {
fn from(_: ()) -> Self {
Self::default()
}
}
impl From<f64> for FooArgs {
fn from(a: f64) -> Self {
Self {
a: a,
..Self::default()
}
}
}
impl From<i32> for FooArgs {
fn from(b: i32) -> Self {
Self {
b: b,
..Self::default()
}
}
}
impl From<(f64, i32)> for FooArgs {
fn from((a, b): (f64, i32)) -> Self {
Self { a: a, b: b }
}
}
pub fn foo<A>(arg_like: A) -> f64
where
A: Into<FooArgs>,
{
let args = arg_like.into();
args.a * (args.b as f64)
}
fn main() {
println!("{}", foo(()));
println!("{}", foo(5.0));
println!("{}", foo(-3));
println!("{}", foo((2.0, 6)));
}
这个选择显然需要更多的代码,但与宏设计不同的是,它使用类型系统,这意味着编译器错误将对您的库/API 用户更有帮助。如果这对他们有帮助,这也允许用户制作自己的 From 实现。