表达式中的 Rust "Not all control paths return a value"

标签 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;
}

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

test.rc:29:0: 1:0 error: not all control paths return a value
error: aborting due to previous error

我觉得这个问题是因为我对“;”的理解不够在 Rust 中以及表达式和语句之间的区别。谢谢!

最佳答案

block 中的最后一条语句作为它的返回值,所以你可以这样做

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

关于表达式中的 Rust "Not all control paths return a value",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20113338/

相关文章:

rust - 使用内联汇编读取 Rust 中 ebx 寄存器的值 ("rbx is used internally by LLVM and cannot be used as an operand for inline asm")

rust - 索引 &str 时为 "error: mismatched types"

rust - 如何将动态数量的类型参数传递给函数?

rust - 如何使用迭代器和范围创建阶乘的非递归计算?

代理后使用rust , "error: no default toolchain configured"

struct - 如何转换作为结构体内部字段的枚举?

rust - Rust 移动语义实际上是如何工作的

pointers - 如何在 Rust 中制作相当于 C 双指针的东西?

rust - 移动的函数参数上的 `mut` 是否会将实现细节泄漏到函数的 API?

rust - 如何链接到 rustdoc 中的其他 fns/structs/enums/traits?