Search code examples
typesrustlinear-search

Can a function return different types depending on conditional statements in the function?


I was wondering if it was possible to return different types depending on the conditions in the function: This code will work if you remove '|| bool' and the 'if/else' statements.

Thanks in advance.

fn main() {
    let vector: Vec<i32> = vec![0, 2, 5, 8, 9];
    let targetL i32 = 3;
    let found_item = linear_search(vector, target);
    println!("{}", &found_item);
}
fn linear_search(vector: Vec<i32>, target: i32) -> i32 || bool {
    let mut found: i32 = 0;
    for item in vector {
        if item == target {
            found = item;
            break
        }
    }
    if found == 0 {
        false
    } else {
        found
    }
}

Solution

  • The precise type must be known at compile time (and is subsequently erased). You cannot decide arbitrarily which types to return at runtime.

    However, you can do you've tried to do, by wrapping the types into a generic enum (which replaces the || in your code):

    enum TypeOr<S, T> {
        Left(S),
        Right(T),
    }
    
    fn linear_search(vector: ...) -> TypeOr<i32, bool> { //...
    

    The downside is that you must unwrap the value from the enum before you can do anything else with the result. However, this isn't so arduous in practice.

    This is essentially a generalised version of the commonly used Option and Result types.

    Edit: In fact, in your case, you are served very nicely by the semantics of the Option type: you never return true, so you may equate the None result with the false result your function returns, and this captures the idea you're trying to express: either your linear search finds the target and returns it (Some(found)), or it does not, and has nothing to return (None).