Creating immutable arrays in @safe code
Ali Çehreli
acehreli at yahoo.com
Sat Jul 17 01:51:39 UTC 2021
On 7/16/21 3:21 PM, Dennis wrote:
> But `pure` is no silver bullet:
Agreed. I occasionally struggle with these issues as well. Here is a
related one:
import std;
void foo(const int[] a) {
auto b = a.array;
b.front = 42;
// Error: cannot modify `const` expression `front(b)`
}
I think that is a Phobos usability issue with array() because the
freshly *copied* int elements are const. Really? So just because the
programmer promised not to modify the parameter, now he/she is penalized
to be *safe* with own data. I am not sure whether array() is the only
culprit with this problem. (I think array() can be improved to pick
mutable type for element types that have no indirections.)
> ```D
> import std;
>
> pure: @safe:
>
> struct Expression
> {
> immutable(Expression)[] children;
> int value;
> }
>
> Expression withSortedChildren(Expression exp)
> {
> return Expression(expr.children.dup.sort!((a, b) => a.value <
> b.value).release);
> }
> ```
>
>> Error: cannot implicitly convert expression
>> `sort(dup(cast(const(Expression)[])expr.children)).release()` of type
>> `Expression[]` to `immutable(Expression)[]`
>
> I've tried structuring it in a way that makes the compiler allow the
> conversion to immutable, but had no luck so far.
I don't have a solution and you have more experience with this. :/
Ali
More information about the Digitalmars-d-learn
mailing list