Write a struct with variable content as the field name

I need to write a bunch of struct with similar name within it. Such as:

pub struct ContactUpdate {
    pub full_name: String,
    pub full_address: String,
    /// .... many other fields
}

pub struct Contact {
    pub contact_id: Option<ObjectId>,
    pub full_name: String,
    pub full_address: String,
    pub created_at: DateTime
    /// .... many other fields
}

/// ... other structs with similar content/field name

I’m lazy. So instead of hard-coding each field name by hand, I think how can I make the field name of the struct into contants with fewer characters so I don’t have to type as much. Also with other benefits to export that constants and use it in other files that need it.

pub const ID: &str = "contact_id";
pub const NAME: &str = "full_name";
pub const TIME: &str = "created_at";
pub const ADDR: &str = "full_address"; 

pub struct Contact {
    pub ID: Option<ObjectId>,
    pub NAME: String,
    pub ADDR: String,
    pub TIME: DateTime
    /// .... many other fields
}

pub struct ContactUpdate {
    pub NAME: String,
    pub ADDR: String,
    /// .... many other fields
}

Is this possible?

>Solution :

No. It is impossible.

If you really want (don’t!) you can have a macro for that.

However, the entire reason for the existence of field names is for the programmers to know what they mean. If you want to use them as constants, you just give them no meaning and can get rid of them completely. At that time, you’re back to the old days where variable name lengths were limited to 7-8 characters and people used all sorts of bad and unreadable codes to work with that. Don’t do that.

Leave a Reply