What type is the “type ()” in Rust?

后端 未结 2 944
余生分开走
余生分开走 2021-01-17 22:21

As a simple exercise to learn Rust, I\'ve decided to implement a simple binary search:

pub fn binary_search(arr: &[i32], key: i32) -> usize {
    let          


        
相关标签:
2条回答
  • 2021-01-17 22:49

    () is the unit type, analogous to a void return type in other languages.

    You're getting it here:

    if key == arr[mid] {
        mid as usize
    }
    

    Rust is expecting that if expression to return (), but you're returning usize for that expression. Since virtually everything in Rust is an expression, you can usually implicit return like you're trying to here, but in this specific case you can't because the if expression is not the only expression in the while expression. You could fix the immediate problem by using return mid as usize; instead.

    0 讨论(0)
  • 2021-01-17 23:10

    () is the unit type or singleton type: it has a single value, also denoted ().

    I personally view it as a tuple with 0 elements.

    Where C or C++ would use void (which has no value) to indicate the return type of a function which returns nothing interesting, Rust uses () instead. This is much nicer to meta-programming, as () is a regular type which accepts values, can be mutated, borrowed, etc...


    Regarding your specific code sample:

    if key == arr[mid] {
        mid as usize
    }
    

    is an expression of type () (because there is no else branch) yet you are attempting to have the if block evaluate to mid as usize which has the type usize thus the compiler notices the mismatch.

    You want to use a return here:

    if key == arr[mid] {
        return mid as usize;
    }
    
    0 讨论(0)
提交回复
热议问题