fn main(){ let x = 123; println!("{}", type_of(x)); } fn type_of<T>(_: T) -> &'static str { std::any::type_name::<T>() }
c++だと、typeid
#include <iostream> #include <typeinfo> struct Base {}; struct Derived : public Base {}; struct PolyBase {virtual void member(){}}; struct PolyDerived : public PolyBase {}; int main() { int i; int* pi; std::cout << "int is: " << typeid(int).name() << std::endl; std::cout << "i is: " << typeid(i).name() << std::endl; std::cout << "pi is: " << typeid(pi).name() << std::endl; std::cout << "*pi is: " << typeid(*pi).name() << std::endl; std::cout << std::endl; Derived derived; Base *pbase = &derived; std::cout << "derived is: " << typeid(derived).name() << std::endl; std::cout << "*pbase is: " << typeid(*pbase).name() << std::endl; std::cout << std::boolalpha << "same type? " << (typeid(derived) == typeid(*pbase)) << std::endl; std::cout << std::endl; PolyDerived polyderived; PolyBase* ppolybase = &polyderived; std::cout << "polyderived is: " << typeid(polyderived).name() << std::endl; std::cout << "*ppolybase is: " << typeid(*ppolybase).name() << std::endl; std::cout << std::boolalpha << "same type? " << (typeid(polyderived) == typeid(*ppolybase)) << std::endl; }
fn main(){ let i = 10; let j = 3.14; println!("{}", type_of(i)); println!("{}", type_of(j)); } fn type_of<T>(_: T) -> &'static str { std::any::type_name::<T>() }
derivedは派生。rustはclassがなくstructとimplなので、baseとderivedという概念があるか不明。。