Type C + 11 decomposition in rust

In C ++ 11, you can decompose a generic type into a value type by removing the semantics of reference / rvalue and cv qualifiers, for example.

decay<int>::type // type is `int`
decay<const int&>::type // type is `int`
decay<int&&>::type // type is `int`

Is there a known mechanism to achieve the same in Rust that separates reference modifiers, lifetimes, and qualifiers mut? eg:.

decay<u32>::type <--- type is `u32`
decay<&u32>::type <--- type is `u32`
decay<&mut u32>::type <--- type is `u32`
decay<&static u32>::type <--- type is `u32`

In the background, I am trying to write a macro that generates struct, which stores the values ​​of a bunch of function arguments matched by the macro. for example, a macro may contain arguments foo: i32, bar: &Vec<String>, and the resulting structure should be:

struct GeneratedStruct {
    foo: i32,
    bar: Vec<String>,
}
+4
source share
1 answer

Matthieu M. kennytm , ( Rust 1.15.0).

#![feature(specialization)]

use std::any::TypeId;

trait Decay {
    type Type;
}

impl<T> Decay for T {
    default type Type = T;
}

impl<'a, T> Decay for &'a T {
    type Type = <T as Decay>::Type;
}

impl<'a, T> Decay for &'a mut T {
    type Type = <T as Decay>::Type;
}

fn foo<T: 'static>() {
    println!("{:?}", TypeId::of::<T>());
}

fn bar<T>() where <T as Decay>::Type: 'static {
    println!("{:?}", TypeId::of::<<T as Decay>::Type>());
}

fn main() {
    foo::<<i32 as Decay>::Type>();
    foo::<<&i32 as Decay>::Type>();
    foo::<<&mut i32 as Decay>::Type>();
    foo::<<&&i32 as Decay>::Type>();

    bar::<i32>();
    bar::<&i32>();
    bar::<&mut i32>();
    bar::<&&i32>();
}
+5

Source: https://habr.com/ru/post/1668927/


All Articles