What is the difference between enum and shared immutable?

Ali Çehreli acehreli at yahoo.com
Thu Oct 29 20:28:26 UTC 2020


On 10/29/20 10:16 AM, H. S. Teoh wrote:

 > Module-level immutable can be initialized either as part of the
 > declaration:
 >
 > 	immutable int x = 1;

To add, the expression can be a call to a function that need not return 
immutable, as long as it is pure, which can be inferred by the compiler 
for templates. Phew! :)

pure char[] makeMutableString() {
   return "hello".dup;
}

// This works because makeMutableString() is 'pure', i.e. 'i' cannot
// share mutable data.
immutable i = makeMutableString();

void main() {
}

So, instead of adding 'pure' to makeMutableString() like above, one can 
add another set of parethesis to make it a template. (Two characters 
instead of four! Win! :p)

char[] makeMutableString()() {
   return "hello".dup;
}

Ali



More information about the Digitalmars-d-learn mailing list