Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Idiomatic way to handle multiple function argument types in 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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

>Solution :

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));
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading