What type of "type ()" in Rust?

As a simple Rust learning exercise, I decided to implement a simple binary search:

pub fn binary_search(arr: &[i32], key: i32) -> usize {
    let min: usize = 0;
    let max: usize = arr.len();
    while max >= min {
        let mid: usize = (max - min) / 2 as usize;
        if key == arr[mid] {
            mid as usize
        }

        if key < arr[mid] {
            min = mid + 1;
            continue;
        }

        max = mid - 1;
    }
    -1 as usize
}

#[cfg(test)]
mod tests {

    use super::binary_search;

    #[test]
    fn binary_search_works() {
        let arr: [i32; 8] = [1, 2, 3, 4, 5, 6, 7, 8];
        let index: usize = binary_search(&arr, 2);
        assert_eq!(1, index);
    }
}

During assembly, I get this error, which I do not understand. What is a type ()? The variable is midalways usize, but even with the drive, asI get this compilation error.

error: mismatched types [E0308]
            mid as usize
            ^~~~~~~~~~~~
help: run `rustc --explain E0308` to see a detailed explanation
note: expected type `()`
note:    found type `usize`
+4
source share
2 answers

() is a unit type similar to the return type voidin other languages.

You get it here:

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

Rust , (), usize . Rust , , , , if while. , return mid as usize; .

+7

() - : , ().

0 .

C ++ void ( ), , , Rust (). , () , , , ..


:

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

() ( else), if mid as usize, usize, .

return :

if key == arr[mid] {
    return mid as usize;
}
+7

Source: https://habr.com/ru/post/1649561/


All Articles