Get type of a variable?

let x = ????;
let v = Vec::< type(x) >::new();

Is there a way to make this work? I want to get the type of a variable and pass it as a type to another expr.

Types in Rust don't exist at run-time, only compile-time.

You could use macros to work out the type, but it needs to be fixed during compilation.

I don't see why this is a problem. The type of x is resolved at compile time, the we substitute it into v , at compile time.

Technically you can achieve this by forcing type inference, for example, when calling a generic function:

fn f1<T>(_value: &T) -> Vec<T> {

fn main() {
    let x = 5;
    let v = f1(&x);

You can trick inference to do it:

let x = ????;
let v = Vec::new();
if false {

Please don't actually do that, though.

Why do you not know what its type is? Can you just copy the type from the error message into there?

1 Like

Possibly futile attempt at solving Compiler error: "specify the associated type"

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.