Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I specify one of possible return types?

Tags:

rust

I have a function that returns one of two structs dependings on some logic. I need to specify the return type to be one of two. How do I do that?

struct A {}

struct B {}

fn picky() -> ??? {
    let a = A{};
    let b = B{};
    if 1 < 10 {
        a
    } else {
        b
    }
}

fn main() {
    picky();
}

This feels like it should be trivial but after hours on Google I still can't figure it out.

like image 573
ilmoi Avatar asked Oct 21 '25 00:10

ilmoi


1 Answers

Your function has only one return type, but this type may be an enum:

struct A {}
struct B {}

enum AB {
    A(A),
    B(B),
}

fn picky() -> AB {
    let a = A{};
    let b = B{};
    if 1 < 10 {
        AB::A(a)
    } else {
        AB::B(b)
    }
}

That's exactly how Result works in Rust: you get either the desired value or an error, because the result is an enum with two variants.

like image 63
Denys Séguret Avatar answered Oct 22 '25 18:10

Denys Séguret



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!