Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Idiomatic way to handle multiple function argument types

Tags:

rust

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.

like image 787
RFTexas Avatar asked Jun 15 '26 22:06

RFTexas


1 Answers

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));
like image 119
JanLikar Avatar answered Jun 19 '26 07:06

JanLikar



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!