是否可以在Rust中的函数中定义可选参数?

Zac*_*ura 3 rust

Rust是否允许可选的函数参数,然后我可以将其设置为某个默认值,例如通过模式匹配或其他一些机制?

abj*_*ror 5

从技术上来说没有,但你可以捎带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
}
Run Code Online (Sandbox Code Playgroud)