#derive #boilerplate #getters

macro derive-getters

Simple boilerplate getters generator

7 releases

0.0.7 Jun 24, 2018
0.0.6 Jun 24, 2018
0.0.4 Apr 28, 2018
0.0.3 Oct 8, 2017
0.0.2 Apr 23, 2017

#52 in Rust patterns

Download history 168/week @ 2018-07-04 187/week @ 2018-07-11 136/week @ 2018-07-18 168/week @ 2018-07-25 121/week @ 2018-08-01 204/week @ 2018-08-08 182/week @ 2018-08-15 115/week @ 2018-08-22 156/week @ 2018-08-29 143/week @ 2018-09-05 153/week @ 2018-09-12 84/week @ 2018-09-19 67/week @ 2018-09-26

975 downloads per month

MIT license

7KB
75 lines

Derive Getters

Simple boilerplate library for getters.

The need for this library came about when I was making various data structures for JSON to deserialize into. These data structures had many fields in them and weren't going to change once created. Of course one could just use pub everywhere.

Getters will be generated according to convention. This means that the generated methods will reside within the struct namespace.

Installation

Add to your Cargo.toml:

[dependencies]
derive-getters = "0.0.7"

Then put this in your rust project root.

#[macro_use]
extern crate derive_getters;

or

#[macro_use] extern crate derive_getters;

PS. This way is better. It makes the code run faster.

Usage

When you have a struct you want to automatically derive getters for... Just add the derive at the top like so;

#[derive(Getters)]
pub struct MyCheesyStruct {
    x: i64,
    y: i64,
}

A new impl will be produced for MyCheesyStruct.

impl MyCheesyStruct {
    pub fn get_x(&self) -> i64 {
        &self.x
    }

    pub fn get_y(&self) -> i64 {
        &self.y
    }
}

Caveats

This crate will not yet create getters for unit structs, tuples or enums. If you try to derive over them, the code will just ignore you and do nothing. (Please let me know by filing an issue if this isn't the right way to handle things. Should this crate panic if attempting to derive on an unsupported value?)

Getters for String fields should return a &str. Right now you have to do an awkward &my_struct.name()[..] to shoehorn it into some semblance of a &str.

Dependencies

~1MB
~26K SLoC