Reputation: 531
I am trying to make properties for immutable fields of structs in my program but I don't like the amount of boilerplate I need to get it working. I just want to make shure there is no shorter way.
struct Foo
{
private immutable int[] bar_;
@property immutable public immutable(int[]) bar() { return bar_;}
this(immutable int[] bar)
{
this.bar_ = bar;
}
}
void main()
{
immutable foo = Foo([0, 1, 2, 3, 4]);
auto bar = foo.bar;
}
I would expect something like
private immutable int[] bar_;
@property public immutable(int[]) bar() { return bar_;}
or even in semi c# style
public immutable int[] bar { get; }
The version I currently have seems like a lot of boilerplate and verry confusing. I hope there is a shorter way of writing a 'bar()' function that I'm just not aware of.
Upvotes: 1
Views: 110
Reputation: 517
You could use the accessors library to generate the setters:
import accessors;
struct Foo
{
@Read("public")
private immutable int[] bar_;
mixin(GenerateFieldAccessors);
}
However, as Adam said you usually don't need or want to use setter and getter properties for immutable
fields.
Upvotes: 3