accessors
module allows to generate getters and setters automatically.
import accessors;
class WithAccessors
{
@Read @Write
private int num_;
mixin(GenerateFieldAccessors);
}
@Read
and @Write
generate the following two methods:
public final inout(int) num() inout
{
return this.num_;
}
public final void num(int num)
{
this.num_ = num;
}
The accessors names are derived from the appropriate member variables by removing an underscore from the beginning or the end of the variable name.
@Read
@RefRead
@ConstRead
@Write
As you can see there are multiple attributes that can be used to generate
getters and only one for the setters. The getters differ by the return
type. @RefRead
returns a ref
to the member variable, @ConstRead
returns a const
value.
Visibility of the generated accessors is by default public
, but it can be
changed. In order to achieve this, you have to pass public
, protected
,
private
or package
as argument to the attribute:
import accessors;
class WithAccessors
{
@Read("public") @Write("protected")
private int num_;
mixin(GenerateFieldAccessors);
}
import accessors;
import std.stdio;
class Person
{
@Read @Write
private uint age_;
@ConstRead
private string name_;
this(in string name, in uint age = 0)
{
this.name_ = name;
this.age_ = age;
}
mixin(GenerateFieldAccessors);
}
void main()
{
auto person = new Person("Saul Kripke");
person.age = 57;
writeln(person.name, ": ", person.age);
}
If you experience compile-time problems, open an issue with the information about the type of the member variable fails.