31
17

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Rustで型の名前を取得する方法

Posted at

1.38からstd::any::type_nameという関数を使って型の名前を取得することができるようになりました。

fn print_typename<T>(_: T) {
    println!("{}", std::any::type_name::<T>());
}

fn main() {
    let a = 42;
    print_typename(a);
    let b = |x: i32| { x * 2 };
    print_typename(b);
    let c = (1..10).skip(2);
    print_typename(c);
}

これをplaygroundで実行すると以下のように出力されます。

i32
playground::main::{{closure}}
core::iter::adapters::Skip<core::ops::range::Range<i32>>

型名を取得できるのはデバッグや学習用に便利かもしれません。ちなみに、std::any::type_nameの返す文字列はコンパイラのバージョンアップで変更の可能性があり、また一意であることも保証されないそうです。

31
17
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
31
17

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?