multiconst/field_querying/
field_type.rs

1/// For querying the type of a field in `Self`.
2///
3/// The name of the field is represented with the `Name` type parameter
4///
5/// The type of nested fields can be queried by passing a tuple of field names.
6///
7/// You can derive this tarit with the [`FieldType`](derive@crate::FieldType)
8/// derive (requires the "derive" feature).
9///
10/// You can use the [`GetFieldType`] type alias as a more convenient way to
11/// get the `Type` associated type.
12///
13/// # Examples
14///
15/// <span id = "manual-impl-example"></span>
16/// ### Manual implementation
17///
18/// This example demonstrates how to make structs easy to destructure in the
19/// [`multiconst`](crate::multiconst) macro without derives.
20///
21/// ```rust
22/// use multiconst::{field_name, multiconst, FieldType};
23///
24/// multiconst!{
25///     const Foo{name: NAME, length: LENGTH}: Foo = Foo {
26///         name: "hello",
27///         length: 123,
28///     };
29/// }
30///
31/// assert_eq!(NAME, "hello");
32/// assert_eq!(LENGTH, 123);
33///
34///
35/// struct Foo {
36///     name: &'static str,
37///     length: usize,
38/// }
39///
40/// impl FieldType<field_name!(name)> for Foo {
41///     type Type = &'static str;
42/// }
43///
44/// impl FieldType<field_name!(length)> for Foo {
45///     type Type = usize;
46/// }
47///
48/// ```
49///
50/// ### Derived
51///
52/// Examples of deriving this trait with the [`FieldType`](derive@crate::FieldType)
53/// derive [are here](derive@crate::FieldType#examples).
54/// (the derive requires the `"derive"` feature)
55///
56///
57///
58pub trait FieldType<Names> {
59    /// The type of the field.
60    type Type;
61}
62
63/// Gets the type of a (potentially nested) field.
64///
65/// The type of nested fields can be queried by passing a tuple of field names.
66///
67/// # Examples
68///
69/// ### Type alias
70///
71/// Gets the type of a field in a type alias
72///
73/// ```rust
74/// use multiconst::{GetFieldType, Usize};
75///
76/// type Foo = (u8, u16, u32, u64, u128);
77///
78/// let _elem0: GetFieldType<Foo, Usize<0>> = 3u8;
79/// let _elem1: GetFieldType<Foo, Usize<1>> = 5u16;
80/// let _elem2: GetFieldType<Foo, Usize<2>> = 8u32;
81///
82/// ```
83///
84/// ### Nested field type
85///
86/// This demonstrates how the type of a nested field is queried.
87///
88/// ```rust
89/// use multiconst::{GetFieldType, Usize};
90///
91/// type Foo = ([u32; 2], (u64, &'static str));
92///
93/// let _elem_0_0: GetFieldType<Foo, (Usize<0>, Usize<0>)> = 3u32;
94/// let _elem_1_0: GetFieldType<Foo, (Usize<1>, Usize<0>)> = 5u64;
95/// let _elem_1_1: GetFieldType<Foo, (Usize<1>, Usize<1>)> = "hello";
96///
97/// ```
98pub type GetFieldType<This, Names> = <This as FieldType<Names>>::Type;