D issues are now tracked on GitHub. This Bugzilla instance remains as a read-only archive.
Issue 6289 - Make slices of const/immutable arrays mutable (but keep the elements const/immutable)
Summary: Make slices of const/immutable arrays mutable (but keep the elements const/im...
Status: RESOLVED FIXED
Alias: None
Product: D
Classification: Unclassified
Component: dmd (show other issues)
Version: D2
Hardware: All All
: P2 enhancement
Assignee: No Owner
URL:
Keywords: patch
Depends on:
Blocks:
 
Reported: 2011-07-11 17:12 UTC by Jonathan M Davis
Modified: 2015-06-09 05:15 UTC (History)
2 users (show)

See Also:


Attachments

Note You need to log in before you can comment on or make changes to this issue.
Description Jonathan M Davis 2011-07-11 17:12:35 UTC
Okay. If you have

immutable val = [1, 2, 3, 4];
void func(immutable(int)[] arg) {}

you can pass val to func even though val is fully immutable. The compiler realizes that it's safe, because func cannot alter the original array. The array in the function is a slice of the original and can't affect the original (since the elements are immutable). However, even though this is true, the type of a slice of an immutable int[], is still immutable int[], not immutable(int)[] as with the function parameter. I'd like to see

immutable val = [1, 2, 3, 4];
assert(is(typeof(val) == immutable(int[])));
assert(is(typeof(val[]) == immutable(int)[]));

The slice is then mutable (though its elements are not) - which makes sense, since that's exactly what the function described above does. The reason that I want this to be the case is that you can then use immutable arrays with range-based functions if you slice them (just as is the case with static arrays). As it stands, both

find(val, 3);

and

find(val[], 3);

are illegal, because the compiler tries to instantiate find with immutable(int[]). But if the type of a slice of val were immutable(int)[], then the second find call would work. This would help solve the problem of immutable arrays not working with range-based functions (see bug# 6148). Then, if you slice static arrays and immutable/const arrays (just as you'd have to do with container), they will work with range-based functions. As it stands, that works with static arrays but not immutable or const arrays.