#struct #field #name

macro struct_field_names

Derive macros for generating the name of each field in a struct and each variant name in an enum as &'static str

3 unstable releases

0.2.1 Jul 5, 2021
0.2.0 Jun 29, 2021
0.1.0 Jun 8, 2021

#1172 in Rust patterns

Download history 7/week @ 2022-04-22 29/week @ 2022-04-29 26/week @ 2022-05-06 68/week @ 2022-05-13 14/week @ 2022-05-20 21/week @ 2022-05-27 37/week @ 2022-06-03 10/week @ 2022-06-10 6/week @ 2022-06-17 14/week @ 2022-06-24 5/week @ 2022-07-01 6/week @ 2022-07-08 5/week @ 2022-07-15 25/week @ 2022-07-22 22/week @ 2022-07-29 16/week @ 2022-08-05

69 downloads per month
Used in struct_field

MIT license

8KB
130 lines

struct_field_names

crates.io

Provides StructFieldNames derive macro.

#[derive(StructFieldNames)]
struct SomeStruct {
    field_one: i32,
    field_two: Vec<bool>,
}

generates

struct SomeStructFieldStaticStr {
    field_one: &'static str,
    field_two: &'static str,
}
impl SomeStruct {
    const FIELD_NAMES: SomeStructFieldStaticStr = SomeStructFieldStaticStr {
        field_one: "field_one",
        field_two: "field_two",
    };
}

which can be used like

let field_one_name: &'static str = SomeStruct::FIELD_NAMES.field_one;
println!("{}", field_one_name);

.

This is useful mostly for typo-proofing.

Credits to the field_types crate. A lot of code here is copied from there.

Usage

Use the StructFieldNames derive macro like this:

#[derive(StructFieldNames)]
struct SomeStruct {
    field_one: i32,
    field_two: Vec<bool>,
}

then access the field name as &'static str like this:

let field_one_name: &'static str = SomeStruct::FIELD_NAMES.field_one;

Use #[struct_field_names(skip)] to skip fields. With

#[derive(StructFieldNames)]
struct Struct {
	field_one: bool,
	#[struct_field_names(skip)]
	field_two: usize,
}

SomeStruct::FIELD_NAMES.field_two won't exist.

Visibility of the field names struct follows your struct.

With

#[derive(StructFieldNames)]
pub struct PublicStruct {
	pub public_field: i32,
	private_field: i32
}
#[derive(StructFieldNames)]
struct PrivateStruct {
	pub public_field: i32,
	private_field: i32
}

only PublicStruct::FIELD_NAMES.public_field would be available to the outside world.

Dependencies

~215–620KB
~15K SLoC