On Wednesday, 30 October 2019 at 11:53:42 UTC, Jacob Carlborg wrote:
On 2019-10-30 00:28, Simen Kjærås wrote:

Something like this?

T readOnce(T)(ref T value) {
     auto tmp = value;
     value = T.init;
     return tmp;
} unittest {
     int i = 3;
     assert(i.readOnce == 3);
     assert(i == 0);
}

Perhaps better to encapsulate it in a struct to avoid someone accessing the value directly.

Quite possibly, but the post was somewhat low on details, and encapsulating it like that does put certain limits on how it can be used, so it's not necessarily the best idea.

FWIW, here's one possible way to do it with a struct:

struct Readonce(T, T defaultValue = T.init) {
    private T value;

    alias get this;

    T get() {
        auto tmp = value;
        value = defaultValue;
        return tmp;
    }

    void get(T newValue) {
        value = newValue;
    }

    this(T newValue) {
        value = newValue;
    }
}

unittest {
    Readonce!(int, -1) a = 3;
    assert(a == 3);
    assert(a == -1);

    a = 3;
    assert(a == 3);
    assert(a == -1);
}

--
  Simen

Reply via email to