Search code examples
genericsrustenumsreturnstructure

How can I return different structure objects from the same function in rust such as python methods which can return anything?


I am a newbee who is trying to learn rust by doing a side project. I am currently trying to return multiple object type from the same function in rust. Please look at the below example:

// I am currently having a base structure A
pub struct A{
    ...
}

// three more structures uses the base structure:
pub struct B{
    a: A,
    s: String
}

pub struct C{
    a: A,
    s: String
}

pub struct D{
    a: A,
    s: String
}

// Now a function I am writing here which needs to return an object of any of the above mention structures i.e. an object of either B,C or D:
fn func(a:A,s:String) -> B or C or D{
    return obj of B
    or return obj of C
    or return obj of D
}

I tried to use enums, but I guess I am not proficient enough in rust to use that. I also tried to use generic types but still not much clear in that area. Any help will be much appriciated... thanks in advance.


Solution

  • Use an enum:

    // your structs A, B, C, D
    
    enum BCD {
        B(B),
        C(C),
        D(D),
    }
    fn func(a:A,s:String) -> BCD {
        let return_b = true;
        let return_c = false;
        if return_b {
            BCD::B(B{ a, s })
        } else if return_c {
            BCD::C(C{ a, s })
        } else {
            BCD::D(D{ a, s })
        }
    }