On Tue, Apr 20, 2021 at 03:56:33PM -0400, Steven Schveighoffer via 
Digitalmars-d-learn wrote:
[...]
> I'm wondering if anyone has a "Write once" type, that is, a type that
> allows you to write it exactly once, and is treated like
> initialization on first setting (i.e. allows writing to previously
> unused const data).

Maybe a const class?  The reference is null until you initialize it by
allocating a new object and initializing it in the ctor.

But sounds like you want a value type instead. Technically, allocating a
const class involves the GC assigning some region of memory to the
class, initializing it, then casting it to const. So I'd imagine that
the by-value equivalent would require a const cast somewhere, probably
in a @trusted block if you want it to work with @safe.

Which means that probably you'll need a @trusted cast somewhere in your
implementation.  So perhaps something like this:

        struct WriteOnce(T) {
                const T payload;
                const bool isSet;

                void opAssign(U : T)(U data)
                in (!isSet)
                {
                        assert(!isSet);
                        @trusted() {
                                *(cast()&payload) = data;
                                *(cast()&isSet) = true;
                        }();
                }
        }


T

-- 
Prosperity breeds contempt, and poverty breeds consent. -- Suck.com

Reply via email to