How to create an overwriteable struct that is always const?
Jonathan M Davis
newsgroup.d at jmdavisprog.com
Sat Jun 1 16:30:12 UTC 2019
On Saturday, June 1, 2019 6:51:08 AM MDT David Zhang via Digitalmars-d-learn
wrote:
> Say I have a struct `S`:
>
> struct S {
> /*const*/ char* pointer;
> ... other members ...
>
> this(/*const*/ char* p, ... others ...) {
> pointer = p;
> ...
> }
> }
>
> What I want, is to be able to use `S` in other data structures
> with the following properties checked by the compiler:
>
> - The variable can be set
> - The variable can be read
> - The variable cannot be modified, only replaced
>
> Is there a type-safe way to do this? If this were a class, I'd
> try std.typecons.Rebindable.
>
> Thanks
If any member variable of a struct is const, then you can't modify that
member ever, and assignment isn't possible unless you override opAssign so
that it overwrites only the mutable members. It's very rare that it makes
sense to make any member variables of a struct const or immutable, because
then you basically can't use assignment anymore.
You could make all of the member variables private and provide no functions
that set any of them, then the only way to change any of their values would
be to construct a new value of that type and assign it to the variable.
If what you really want is const(S)* though, then it would be simplest to
just use const(S)*, though that requires allocating. Rebindable only exists,
because the language basically conflates a reference to the class object
with the class object itself, meaning that you can't make the class object
const without making the reference const.
- Jonathan M Davis
More information about the Digitalmars-d-learn
mailing list