Is it possible to pass a data type as an argument?

So for example (this is in pseudo code):

some_function("string", u32);

Is it possible to have a function that takes a datatype as an argument?

No, not like that. You are probably trying to write a generic function?

fn some_function<T>(arg: &str) {
   ...
}

some_function::<u32>("string");
2 Likes

You can consider type parameters to be some sort of "types being passed as arguments". In Rust, however, types are not values, so some things are different, in particular the syntax (as shown in @H2CO3's example).

Here another example which uses some of the functions provided by the std::any module (but not needing the Any trait):

use std::any::{TypeId, type_name};

struct MyType;

fn takes_type<T: 'static>() {
    if TypeId::of::<T>() == TypeId::of::<String>() {
        println!("Got a String.");
    } else if TypeId::of::<T>() == TypeId::of::<MyType>() {
        println!("Got MyType.");
    } else {
        println!("Got some other type: {}", type_name::<T>())
    }
}

fn main() {
    takes_type::<String>();
    takes_type::<MyType>(); // we pass the type `MyType` here, not the value `MyType`
    takes_type::<i32>();
}

(Playground)

Output:

Got a String.
Got MyType.
Got some other type: i32

Note that TypeId is buggy yet, see #10389.

1 Like

Datatype doesn't exist after program compilation thus it can not be, of course, passed as argument.

Generic functions accept data types as aguments, but they can only do operations with types in the program compilation time and not in runtime.

That's not the only approach possible: Zig uses a different scheme, some argue it's strictly better, some argue it's worse.

Only time would show whether Zig's approach works.

1 Like