是否可以在Rust中的函数中定义可选参数?(Is it possible to define optional arguments within functions in Rust?)

编程入门 行业动态 更新时间:2024-10-26 10:28:55
是否可以在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 }

更多推荐

本文发布于:2023-07-04 16:50:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1026856.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:可选   函数   定义   参数   Rust

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!