Rust"表达式中并非所有控制路径都返回值"

Lee*_*ter 2 rust

我有以下代码:

//returns GREATER if x is greater than y
//LESS if x is less than y
//EQUAL if x == y
fn less_or_greater(x: int, y: int) -> &str{
    let result = 
        if x == y {
            "EQUAL"
        }
        else if x > y{
            "GREATER"
        }
        else {
            "LESS"
        }; 
    return result;
}
Run Code Online (Sandbox Code Playgroud)

如何使用不包括return语句的推荐Rust样式从此函数返回?如果我不包含它,我会得到以下编译错误:

test.rc:29:0: 1:0 error: not all control paths return a value
error: aborting due to previous error
Run Code Online (Sandbox Code Playgroud)

我认为这个问题是由于我对";"缺乏了解 在Rust和表达式和语句之间的区别.谢谢!

小智 7

块中的最后一个语句充当其返回值,因此您可以这样做

fn less_or_greater(x: int, y: int) -> &'static str {
    if x == y {
        "EQUAL"
    } else if x > y {
        "GREATER"
    } else {
        "LESS"
    }
}
Run Code Online (Sandbox Code Playgroud)

  • 只要你在声明的最后留下分号.我想这样做不会引入一个新的空语句,没有/ unit值. (2认同)