On Tuesday, 10 July 2018 at 13:41:56 UTC, FeepingCreature wrote:
I've written up a short blogpost about the T.init issue.

It is not very enthusiastic.

https://medium.com/@feepingcreature/d-structs-dont-work-for-domain-data-c09332349f43

Related links:

https://github.com/dlang/phobos/pull/6594 problem with T.init and toString

https://github.com/dlang/phobos/pull/6619 Nullable can't work with types where T.init violates invariants

https://github.com/dlang/dmd/pull/8462 A somewhat sketchy PR to disable invariant on struct ~this

First of all I must point that I would very much like to have seen a code actually producing an error in that article. Contrary to what is hinted just taking the struct and putting using it with Nullable or format() caused no error for me and worked as expected. Taking .init explicitely was the only thing that actually caused an error. I'm not saying you didn't experience these issues, but if you want to demonstrate a problem then please demonstrate it.

That said, I may be missing something obvious but what prevents you from overloading the init field?

    struct MyDomainData {
        string username;
@disable this(); // don't make a MyDomainData() by accident!
        this(string username)
        in(!username.empty) // only non-empty usernames please!
        do { this.username = username; }
        // let's formalise the restriction.
        invariant { assert(!username.empty); }
        string toString() { ... }

        static @property MyDomainData init() {
            return MyDomainData("uninitialized");
        }

        ...
    }

    auto test = MyDomainData.init;  // There, no error

Of course that value means nothing but .init isn't meant to actually mean something anyway, it's just a valid value and that's what that init is proposing, so it shouldn't cause any more bugs than empty .init in a normal case.

Reply via email to