-
-
Notifications
You must be signed in to change notification settings - Fork 2.6k
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Ability to make struct members readonly when referenced from another namespace #2479
Comments
Related: #2059 Making fields read-only outside a package is an interesting alternative/compromise to fully private fields. I've considered it before but haven't experimented with actually using it yet. I'd recommend a more obvious qualifier such as |
I've been meaning to propose something like this myself! |
I have two other ideas on how to achieve this: |
This is one of those things where zig is going to not provide a language feature that, admittedly, could be useful, but ultimately is unnecessary to accomplish zig's goals. |
Typedef could be viable for this use case (#5132). See that issue for explanation of the syntax const ProtectedStruct = typedef(OrigStruct, .Encapsulated{.mode = .FieldsReadOnly} );
test "encapsulated struct" {
// auto coercion from base to typdef allowed in the context
// of encapsulation, but casting is required in the other direction.
const ps : ProtectedStruct = OrigStruct.init();
ps.field1 += 1; // compile error
_ = ps.field1; // ok
} Then you would set
This typedef feature would require the compiler to "consult" what typedef config is associated with |
Imagine a struct instance with fields that must stay internally consistent. Then it would be helpful to be able to mark these fields as "read only" when referenced outside their own "class/namespace/struct".
This feature is arguably just about helping developers discipline themselves. So it might be out of scope for a low-level oriented language like zig. Though at the same time, this kind of feature can be very helpful for maintainability in larger projects, if that is within zig's scope.
The text was updated successfully, but these errors were encountered: