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

1

9

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
    }
}
Poplin answered 28/10, 2015 at 11:55 Comment(0)
R
17

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

Riven answered 28/10, 2015 at 12:0 Comment(2)
Thank you both, in this case Option looks cleaner, but if i understand it right: with enum you have more optionsPoplin
@user3419211 in your case you should definitely use Option. The raw enum has more options (and can be nested, etc) but Option is in the standard library and it's use there matches your use case exactly.Riven

© 2022 - 2024 — McMap. All rights reserved.