How can i declare a variable that has two types

Hello everyone

i would like to create a hashmap, who's value tells which parts of the code to invoke

example of how i intend to use it

match -> { to: "animal::cat" | closure }

here i have a hashmap <String, String|Closure> when the match is found, i check the value, if its a string, i do another match to find what module the string point to, if its a closure i invoke it, the closure can have any number of parameters (unknown)

how can i achieve this behavior in rust?

1 Like

In general everything can be of only one exact type.
However, Rust has enums which allow you to express different variants, and on top of that each variant can hold additional data:

enum Value<F> {
  String(String), // The outer `String` is your variant name, the inner one is the Rust String type
  Closure(F), // F is a generic type and would be your closure type.

See the book on enums.
You can later check which variant your variable has:

match map.get("value") {
  Value::String(s) => println!("contained a string: {}", s),
  Value::Closure(f) = > panic!("can't handle the rest yet"),

Now closures need to be one of the closure types. See the closure chapter.
You can't express "any number of parameters" though. How would you even call it if you don't know what to pass in?

I hope that helps.

1 Like

If all your parameters have the same type (or all parameters are only from a specific set of types) you could use some collection type in order to pass them to the function (for example a Vec)

1 Like

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.