是否可以在Rust中的函数中定义可选参数?(Is it possible to define optional arguments within functions in Rust?)
Rust是否允许可选的函数参数,然后我可以将其设置为某个默认值,例如通过模式匹配或其他一些机制?
Does Rust allow for optional function arguments, which I can then set to some default value, such as through pattern matching or some other mechanism?
最满意答案
技术上没有,但你可以捎带Option枚举,它始终可用于实现类似的效果:
fn opt_arg(i: Option<int>) { match i { Some(x) => { println!("Got {}", x); }, None => { println!("Didn't get anything"); } } } fn main() { opt_arg(None); // Didn't get anything opt_arg(Some(2i)); // Got 2 }Technically no, but you can piggyback off the Option enum which is always available to achieve a similar effect:
fn opt_arg(i: Option<int>) { match i { Some(x) => { println!("Got {}", x); }, None => { println!("Didn't get anything"); } } } fn main() { opt_arg(None); // Didn't get anything opt_arg(Some(2i)); // Got 2 }更多推荐
发布评论