RFTexas
RFTexas

Reputation: 310

Idiomatic way to handle multiple function argument types

I'm fairly new to Rust and I would need some guidance on how to handle multiple types for one argument in Rust. I don't even know if that is possible.

I have a function that does a bunch of computations and whose some instructions may vary based on the type of an argument.

In Python, it would read:

def foo(bar):
   # Do a bunch of computations
   if isinstance(bar, TYPE_A):
       # Do this
   elif isinstance(bar, TYPE_B):
       # Do that

I don't even know if that is possible in Rust or even recommended. The function body is quite substantial and it seems cleaner to handle this type-based condition using a match statement within the function body rather than having two very similar functions that support two different types.

I'm not looking for generics here. Actually in my case, Type_A is a Rust ndarray instance and TYPE_B would be a custom struct.

Upvotes: 8

Views: 4947

Answers (1)

JanLikar
JanLikar

Reputation: 1306

Without generics your best bet would be to define an enum containing both variants.

enum MyParam {
    TypeA(ndarray),
    TypeB(SomeStruct),
}

Body of the function would be something like:

fn my_func(param: MyParam) {
    match param {
        TypeA(my_narray) => {
           ...
        },
        TypeB(my_struct) => {
           ...
        },
    }
}

And you would call it like

my_func(MyParam::TypeA(the_array));
my_func(MyParam::TypeB(the_struct));

Upvotes: 13

Related Questions