On Friday, 9 February 2018 at 17:31:47 UTC, Adam D. Ruppe wrote:
On Friday, 9 February 2018 at 16:44:32 UTC, Seb wrote:
Forget inout, it's seldomly used and there have even attempts to remove it from the language.

inout rox. I think this is more of a documentation discoverability problem. We should be having people read the spec, which is written toward compiler authors [!], when they want to just know how to use it.

Here's the basic rules of thumb:

If you don't need to change a variable:

1) use immutable when declaring a new variable

immutable myvar = "never gonna change";

2) if you are returning a member variable or function argument, use inout on both

class myclass {
   Object member;
   inout(Object) getMember() inout {
       return member;
   }
}

inout(char)* identity(inout(char)* s) {
   return s;
}

My main issue with inout is the following:

struct Option(T)
{
    bool isNull;
    T payload;

    this(inout(T) val) inout
    {
        payload = val;
    }

    bool opEquals(inout(T) val) inout
    {
        return !this.isNull && (this.get() == val);
    }

    inout(T) get() inout
    {
        return payload;
    }
}

struct InoutHeaven
{
    int n;
}

void main()
{
    immutable Option!InoutHeaven v1 = InoutHeaven(1);
    assert(v1 == InoutHeaven(1));
}

Everything is fine until InoutHeaven defines a custom opEquals:

struct InoutHell
{
    int n;

    bool opEquals(InoutHell other)
    {
        return n == other.n;
    }
}

void main()
{
    immutable Option!InoutHell v1 = InoutHell(1);
    //Welcome to Inout Hell >:^)
//Error: mutable method onlineapp.InoutHell.opEquals is not callable using a inout object
    assert(v1 == InoutHell(1));
}

The really frustrating thing is that as far as I know, there's nothing you can do if you don't have control over the wrapped type. If you can't add your own inout or const opEquals method, you're screwed.

I might be wrong about this though, as I think Steven has debunked this on at least one occasion. However, I can't remember what his solution was, if there was one.

Reply via email to