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.
You can use the macro in the following manner:
```rust
struct Foo {
#[get(clone)]
bar: String,
#[get(copy)]
pub baz: f32,
#[get(imref(&Path), mutref(&mut Path))]
qux: PathBuf
#[set]
pub quux: Option
These should effectively translate to:
rust
impl Foo {
fn get_bar(&self) -> String {
self.bar.clone()
}
pub fn get_baz(&self) -> String {
self.baz.clone()
}
fn get_qux_ref(&self) -> &Path {
self.qux.as_ref()
}
fn get_qux_ref_mut(&self) -> &mut Path {
self.qux.as_mut()
}
pub fn set_quux(&mut self, value: Option<u64>) {
self.quux = value
}
}
Each field can only have atmost one #[get(..)]
attribute and atmost one #[set]
attibute.
So, This is fine
```rust ...
corge: i32
...
This is not!
rust
...
corge: i32 ... ```
Arguments copy
, clone
, im_ref
and mut_ref
can only be present at most once, inside an attribute.
copy
and clone
can be used inside the same attribute.im_ref
and mut_ref
also require a rust type, which is the return type of the getter.im_ref
simply calls the AsRef
impl of that type. Similarily mut_ref
calls the AsMut
impl.copy
or clone
, the name of the getter will simply be get_<field_name>
, where <field_name>
is replaced by the name of the field on which the attribute is present. (See the above example)im_ref
, the name of the getter will be get_<field_name>_ref
, and get_<field_name>_ref_mut
in case of mut_ref
#[set]
does not take any arguments and the name of the setter generated is set_<field_name>
.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.
```rust ...
grault: Result
garply: Option
These effectively translate to:
rust
...
fn get_grault_opt(&self) -> Option<i32> {
self.grault.ok()
}
fn get_garply_mut_opt(&mut self) -> Option<&mut i32> {
self.garply.as_mut()
}
...
You must be careful while using this, because technically you can do things like:
```rust ...
let foo = *waldo;
let bar = (foo * 420) as f32;
*waldo = (bar - 1.69) as i32;
bar
} => f32))] pub waldo: i32 ... ```
This will translate to something like
rust
...
pub fn get_waldo_funk(&mut self) -> f32 {
let foo = *self.waldo;
let bar = (foo * 420) as f32;
self.waldo = (bar - 1.69) as i32;
bar
}
...