On Tuesday, 15 September 2015 at 17:45:45 UTC, Freddy wrote:
Would it be worth implementing some kind of typestate into the language?
By typestate I mean a modifiable enum.

For example:
---
enum FState
{
    none,
    read,
    write
}

struct File
{
    //maybe another keyword other than enum
    enum state = FState.none;

    void openRead(string name)
    {
        //evalutaed in a way similar to static if
        state = FState.read;
        //...
    }

    void openWrite(string name)
    {
        state = FState.write;
        //...
    }

    ubyte[] read(size_t) if (state == FState.read)
    {
        //...
    }

    void write(ubyte[]) if (state == FState.write)
    {
        //...
    }
}

unittest
{
    File f;
    static assert(f.state == FState.none);
    f.openRead("a.txt");
    static assert(f.state == FState.read);
    auto data = f.read(10);
}
---

We could use this "typestate" to implement:
 Rust style memory management in a library
 Safer Files (as shown)
 Possibly other ideas

Thoughts?

This won't work in D. Everything that's static is common to each instance. What's possible however is to use an immutable FState that's set in the ctor.

---
struct File
{
    immutable FState state,
    this(string fname, FState st){state = st}
}
---

Than you're sure that your file state can't be changed by error.
Otherwise just hide the state to set it as a private variable...

Reply via email to