Are semicolons optional in Rust?

前端 未结 2 448
渐次进展
渐次进展 2020-11-27 16:20

Since semicolons are apparently optional in Rust, why, if I do this:

fn fn1() -> i32 {    
    let a = 1
    let b = 2
    3
}

I get the

2条回答
  •  清酒与你
    2020-11-27 16:30

    Semicolons are generally not optional, but there are a few situations where they are. Namely after control expressions like for, if/else, match, etc.

    fn main() {
        let a: u32 = 5;
        if 5 == a {
            println!("Hello!");
        }
        if 5 == a {
            println!("Hello!");
        };
        for x in "World".chars() {
            println!("{}", x);
        }
        for x in "World".chars() {
            println!("{}", x);
        };
    }
    

    https://play.rust-lang.org/?version=stable&mode=debug&edition=2018&gist=1bf94760dccae285a2bdc9c44e8f658a

    (There are situations where you do need to have or not have semicolons for these statements. If you're returning the value from within you can't have a semicolon, and if you're setting a variable to be the value from within you'll need a semicolon.)

提交回复
热议问题