On Your Marks.. Get Set.. Rust!
Things might break and error handling is primitive. Use at your own risk
This library provides a single macro GetSet, which allows you to write rudimentary getters and setters for your struct.
I wrote this because I was tired of manually writing them. In most cases, you would not need getters and setters which are this primitive but I needed them (and also "muh proc-macros" ¯\_(ツ)_/¯).
If you find a bug or have a feature which seems like a good fit, feel free to contribute.
Basic Usage
You can use the macro in the following manner:
These should effectively translate to:
Remarks
-
Each field can only have atmost one
#[get(..)]attribute and atmost one#[set]attibute.So, This is fine
... corge: i32 ...This is not!
... corge: i32 ... -
Arguments
copy,clone,im_refandmut_refcan only be present at most once, inside an attribute. -
Arguments
copyandclonecan be used inside the same attribute. -
Arguments
im_refandmut_refalso require a rust type, which is the return type of the getter. -
Argument
im_refsimply calls theAsRefimpl of that type. Similarilymut_refcalls theAsMutimpl. -
If the Argument is either
copyorclone, the name of the getter will simply beget_<field_name>, where<field_name>is replaced by the name of the field on which the attribute is present. (See the above example) -
Similarly Argument is
im_ref, the name of the getter will beget_<field_name>_ref, andget_<field_name>_ref_mutin case ofmut_ref -
Attribute
#[set]does not take any arguments and the name of the setter generated isset_<field_name>. -
All the methods generated have
pubvisibility.
Funky
There also exist a special getter argument - funky, which allows you to do funky stuff (duh).
This allows you to use any rust expression to manipulate the value, which you are getting.
...
grault:
garply:
...
These effectively translate to:
...
...
You must be careful while using this, because technically you can do things like:
...
pub waldo: i32
...
This will translate to something like
...
...
Remarks
- This is the only argument which can occur more than once.
funkytakes :- identifier which will be used to create the name of the getter,
- then, the
::symbol - then, an optional
mutkeyword which specifies if the reciever is&mut selfor&self - then, the
=>symbol - then, the return type of the getter
- I only added this, because i find myself often needing getters which call a single method on a field and return that value (See the example)
- Probably do not use if you need to do more than one line of processing on the field value (or use it if you are lazy like me :D)