Return different types

Hello there,

I'm trying to write a function that should return a different types depending on a condition. A straightforward example is finding the median of a slice:

fn median_finding_nlogn(v: &mut[i32]) -> f32 {
    let l = v.len();
    v.sort();
    if l % 2 == 1 {
        return v[l / 2] as f32;
    }
    return (v[l / 2] + v[(l / 2) - 1]) as f32 / 2.0
}

Here, if the length of the slice is odd, I know that my median will be the middle element, which is a i32; instead, if the length of the slice is even, the median will (possibily) be a f32 number. Although this is not strictly related to Rust, is there a way to handle these two types in the return value?

Heya, you can use an enum (see sum types):

enum FloatOrI32 {
    F32(f32),
    I32(i32)
}

fn median_finding_nlogn(v: &mut[i32]) -> FloatOrI32 {
    let l = v.len();
    v.sort();
    if l % 2 == 1 {
        return FloatOrI32::I32(v[l / 2]);
    }
    return FloatOrI32::F32((v[l / 2] + v[(l / 2) - 1]) as f32 / 2.0)
}

playground

2 Likes

In addition to returning an enum, if you intend to match on the enum directly afterwards, I recommend adding #[inline] to the function. Inlining enables the optimizer to remove the enum and match, which is generally what you want.

This is exactly what I was looking for! Thank you!

1 Like

Thanks for this

Hey, I think you mixed up the cases in your example code. The case with the division is the one that needs to keep the as f32 and be wrapped in the F32 variant.

1 Like

oh woops, it is the other way round
shall fix it, thank you :bowing_man: