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

后端 未结 2 946
余生分开走
余生分开走 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.

提交回复
热议问题