30

I have a custom struct like the following:

struct MyStruct {
    first_field: i32,
    second_field: String,
    third_field: u16,
}

Is it possible to get the number of struct fields programmatically (like, for example, via a method call field_count()):

let my_struct = MyStruct::new(10, "second_field", 4);
let field_count = my_struct.field_count(); // Expecting to get 3

For this struct:

struct MyStruct2 {
    first_field: i32,
}

... the following call should return 1:

let my_struct_2 = MyStruct2::new(7);
let field_count = my_struct2.field_count(); // Expecting to get count 1

Is there any API like field_count() or is it only possible to get that via macros?

If this is achievable with macros, how should it be implemented?

Shepmaster
  • 388,571
  • 95
  • 1,107
  • 1,366
Akiner Alkan
  • 6,145
  • 3
  • 32
  • 68
  • 2
    What is the *purpose* of doing this? The language is statically typed, so the function would be constant, that is you'd always get the same answer and there is no useful decision to be made based on that. – Jan Hudec Jan 14 '19 at 08:25
  • 5
    @Jan Hudec, Let's say you have written statically the count on some different blocks of the program and at some time you change the struct and added a new field. Then, I do not want to edit the count on everywhere else which can be automaticlly handled – Akiner Alkan Jan 14 '19 at 08:36
  • 1
    That still does not say what is a use for this information at all in the first place. Any code that depends on the number of fields will depend on it at compile-time, and will probably depend on the types and names of the fields too. When the fields change, it will either fail to compile, or it is generated, in which case the generator needs the information-and custom derive is the right tool for that. – Jan Hudec Jan 14 '19 at 09:42

2 Answers2

31

Are there any possible API like field_count() or is it only possible to get that via macros?

There is no such built-in API that would allow you to get this information at runtime. Rust does not have runtime reflection (see this question for more information). But it is indeed possible via proc-macros!

Note: proc-macros are different from "macro by example" (which is declared via macro_rules!). The latter is not as powerful as proc-macros.

If this is achievable with macros, how should it be implemented?

(This is not an introduction into proc-macros; if the topic is completely new to you, first read an introduction elsewhere.)

In the proc-macro (for example a custom derive), you would somehow need to get the struct definition as TokenStream. The de-facto solution to use a TokenStream with Rust syntax is to parse it via syn:

#[proc_macro_derive(FieldCount)]
pub fn derive_field_count(input: TokenStream) -> TokenStream {
    let input = parse_macro_input!(input as ItemStruct);

    // ...
}

The type of input is ItemStruct. As you can see, it has the field fields of the type Fields. On that field you can call iter() to get an iterator over all fields of the struct, on which in turn you could call count():

let field_count = input.fields.iter().count();

Now you have what you want.

Maybe you want to add this field_count() method to your type. You can do that via the custom derive (by using the quote crate here):

let name = &input.ident;

let output = quote! {
    impl #name {
        pub fn field_count() -> usize {
            #field_count
        }
    }
};

// Return output tokenstream
TokenStream::from(output)

Then, in your application, you can write:

#[derive(FieldCount)]
struct MyStruct {
    first_field: i32,
    second_field: String,
    third_field: u16,
}

MyStruct::field_count(); // returns 3
hellow
  • 12,430
  • 7
  • 56
  • 79
Lukas Kalbertodt
  • 79,749
  • 26
  • 255
  • 305
  • 1
    Instead of a derive, you can also make it a custom attribute, see [the reference](https://doc.rust-lang.org/reference/procedural-macros.html#attribute-macros) for details – hellow Jan 14 '19 at 08:37
  • Note: run-time reflection is not necessary, run-time introspection or even compile-time introspection would be sufficient. And indeed, it turns out that using a derive/attribute/proc-macro is compile-time introspection. – Matthieu M. Jan 14 '19 at 10:26
  • 1
    I couldn't find similar functionality on crates.io. So, I packaged this answer into the following crate: https://github.com/discosultan/field-count. Hope it's useful to someone as it's impossible to add a new proc_macro definition to a library which exports stuff other than macros. Thank you @lukas-kalbertodt. – Jaanus Varus Sep 22 '20 at 19:15
9

It's possible when the struct itself is generated by the macros - in this case you can just count tokens passed into macros, as shown here. That's what I've come up with:

macro_rules! gen {
    ($name:ident {$($field:ident : $t:ty),+}) => {
        struct $name { $($field: $t),+ }
        impl $name {
            fn field_count(&self) -> usize {
                gen!(@count $($field),+)
            }
        }
    };
    (@count $t1:tt, $($t:tt),+) => { 1 + gen!(@count $($t),+) };
    (@count $t:tt) => { 1 };
}

Playground (with some test cases)

The downside for this approach (one - there could be more) is that it's not trivial to add an attribute to this function - for example, to #[derive(...)] something on it. Another approach would be to write the custom derive macros, but this is something that I can't speak about for now.

Cerberus
  • 8,879
  • 1
  • 25
  • 40