On 07/05/2018 01:00 PM, ag0aep6g wrote:

> `immutable` means that the data can't ever change. Not even the owning
> Foo is allowed to change it. If you want to disallow changes from
> outside, but still allow the owning Foo to make changes, use `const`:
>
>      static const(Foo[]) getFooList()

To add, in that context 'immutable' would be a guarantee to the outside world: "I will never change this data." On the other hand, 'const' means "Dear compiler, please make sure the caller does not mutate this data."

However, I think the return type would be more useful as const(Foo)[] to let the caller to be able to add elements to their local copy of the slice:

struct Foo {
}

Foo[] foos;

// const(Foo[]) would not allow the concatenation in main.
const(Foo)[] getFooList() {
    return foos;
}

void main() {
    auto f = getFooList();
    f ~= Foo();
}

But then one might argue that if the caller would concatenate anyway, which would cause memory allocation and copying, wouldn't the caller better use .dup to get a mutable copy of the elements.

    auto f = getFooList().dup;
    f ~= Foo();

I don't know... Too much analysis... :)

Ali

Reply via email to