typeof in Rust

Mattepuffo's logo
typeof in Rust

typeof in Rust

Può capitare, soprattutto quando si studia un nuovo linguaggio, di dover capire con che tipo di variabile abbiamo a che fare.

Rust non ha una funzione specifica per il typeof, ma è comunque molto semplice "crearla" usando type_name.

Ecco un esempio:

use std::any::type_name;

fn type_of<T>(_: T) -> &'static str {
    type_name::<T>()
}

fn main() {
    let x = 10;
    let y = 10.5;
    let s = "CIAO";
    println!("{}", type_of(&y));
    println!("{}", type_of(x));
    println!("{}", type_of(s));
}

Enjoy!


Condividi

Commentami!