Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What type is the "type ()" in Rust?

Tags:

rust

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 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);
    }
}

At build time, I get this error which I do not understand. What is the () type? Variable mid is always usize but even with the as cast I'm getting 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`
like image 890
revington Avatar asked Jul 29 '16 16:07

revington


People also ask

What is type () in Rust?

The () type, also called “unit”. The () type has exactly one value () , and is used when there is no other meaningful value that could be returned. () is most commonly seen implicitly: functions without a -> ... implicitly have return type () , that is, these are equivalent: fn long() -> () {} fn short() {}

How do you know what type you are in Rust?

Rust types are represented by the Ty and TyKind types. You use Ty to represent "some Rust type". But to actually inspect what sort of type you have, you invoke the kind method, which returns a TyKind .

What are primitive types Rust?

Rust has two primitive compound types: tuples and arrays.

How do you declare a variable type in Rust?

Declaring a variable In Rust, we can create variables by assigning data to alphanumeric words( excluding keywords) using the let keyword or const keyword. Syntax: let x = "Value"; or const x = "Value"; Example: Rust.


1 Answers

() 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.

like image 165
Aurora0001 Avatar answered Dec 26 '22 09:12

Aurora0001