D issues are now tracked on GitHub. This Bugzilla instance remains as a read-only archive.
Issue 10880 - foreach on matrix literal refuses immutable iteration
Summary: foreach on matrix literal refuses immutable iteration
Status: NEW
Alias: None
Product: D
Classification: Unclassified
Component: dmd (show other issues)
Version: D2
Hardware: All All
: P4 enhancement
Assignee: No Owner
URL:
Keywords:
Depends on:
Blocks:
 
Reported: 2013-08-24 08:55 UTC by bearophile_hugs
Modified: 2024-12-13 18:10 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 bearophile_hugs 2013-08-24 08:55:18 UTC
A matrix literal can be assigned to an immutable, but this isn't done in a foreach:


void main() {
    immutable m1 = [[1]]; // OK
    foreach (immutable v; [[1]]) {} // error
}


dmd 2.064alpha gives:

test.d(3): Error: cannot implicitly convert expression (__aggr4[__key5]) of type int[] to immutable(int[])
Comment 1 yebblies 2013-11-20 07:44:52 UTC
And nor should it.  As the error says, [[1]] has type int[][], and you can't implicitly convert int[] to immutable(int[]).

Asking for initializer-style type inference is an enhancement, and doesn't work particularly well with the way foreach expands to for.

Alternatives are to use const, or give the aggregate expression an explicit type.
Comment 2 bearophile_hugs 2013-11-20 08:07:34 UTC
(In reply to comment #1)

> Asking for initializer-style type inference is an enhancement,

OK.


> and doesn't work
> particularly well with the way foreach expands to for.

If you think this enhancement request is too much work to implement, or it causes other troubles, then close this ER down.
Comment 3 Meta 2013-11-20 14:25:52 UTC
(In reply to comment #1)
> And nor should it.  As the error says, [[1]] has type int[][], and you can't
> implicitly convert int[] to immutable(int[]).
> 
> Asking for initializer-style type inference is an enhancement, and doesn't work
> particularly well with the way foreach expands to for.
> 
> Alternatives are to use const, or give the aggregate expression an explicit
> type.

In this case, isn't [[1]] a unique expression, so it can be implicitly cast to immutable? Also, foreach (const v; [[1]]) works, but this doesn't (and it probably should):

class Test
{
}

foreach (const v; [new Test()])
Comment 4 dlangBugzillaToGithub 2024-12-13 18:10:52 UTC
THIS ISSUE HAS BEEN MOVED TO GITHUB

https://github.com/dlang/dmd/issues/18658

DO NOT COMMENT HERE ANYMORE, NOBODY WILL SEE IT, THIS ISSUE HAS BEEN MOVED TO GITHUB