nice how D's pieces fit together
anonymous
anonymous at example.com
Thu Mar 14 19:31:28 PDT 2013
Just a little newbie aha moment I'd like to share.
I was about to post this:
>int[] f() {return [1, 2, 3];}
>
>As far as I understand, f returns a fresh array on each call,
>and therefore, it should be safe to store the result in an
>immutable variable.
>
>Unfortunately, this fails: immutable v = f();
>"Error: cannot implicitly convert expression (f()) of type int[]
>to immutable(int[])"
>
>I could cast explicitly, of course: auto v = cast(immutable) f();
>But can the cast be avoided?
Then it struck me:
The compiler doesn't know that f's return value is unknown to the
rest of the world, because f isn't marked pure.
And, indeed, make f pure and it just works: int[] f() pure
{return [1, 2, 3];} immutable v = f();
Awesome!
More information about the Digitalmars-d-learn
mailing list