Make a variable single-assignment?

Robert Clipsham robert at octarineparrot.com
Mon Nov 21 10:08:09 PST 2011


On 21/11/2011 14:04, Alex Rønne Petersen wrote:
> Hi,
>
> Is there any way to make a variable single-assignment, regardless of its
> type? I.e.:
>
> void foo()
> {
> <some magical keyword?> int i = 0;
> i = 2; // Error: i cannot be reassigned
> }
>
> I realize const and immutable will do this, but they are transitive and
> infect the type, which I do *not* want. I simply want the variable to be
> single-assignment. Is it possible?
>
> - Alex

In D1 you could use final, in D2 your choices are either const, 
immutable, or as others have suggested, some sort of a wrapper. You 
could also use enum if you only want to work with primitive types and 
the value can be calculated at compile time.

-- 
Robert
http://octarineparrot.com/


More information about the Digitalmars-d-learn mailing list