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

后端 未结 2 964
余生分开走
余生分开走 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 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;
    }
    

提交回复
热议问题