digitalmars.D.learn - enum VS static immutable
- ref2401 (10/10) Mar 13 2014 Hi.
- w0rp (7/17) Mar 13 2014 enum is a compile-time constant. 'static immutable' is an
- ref2401 (1/1) Mar 13 2014 thank you
- =?UTF-8?B?QWxpIMOHZWhyZWxp?= (16/26) Mar 13 2014 enum defines a manifest constant, meaning that it is just a value; there...
Hi. I have this structure: struct MyStruct { enum MyStruct VALUE = MyStruct(5f); static immutable MyStruct value = MyStruct(5f); float data; this(float v) { data = v; } } What's the difference between MyStruct.VALUE and MyStruct.value? How should I decide what to use?
Mar 13 2014
On Thursday, 13 March 2014 at 14:38:27 UTC, ref2401 wrote:Hi. I have this structure: struct MyStruct { enum MyStruct VALUE = MyStruct(5f); static immutable MyStruct value = MyStruct(5f); float data; this(float v) { data = v; } } What's the difference between MyStruct.VALUE and MyStruct.value? How should I decide what to use?enum is a compile-time constant. 'static immutable' is an immutable (and therefore implicitly shared between threads...) runtime constant that isn't part of the struct itself. I'd stick with enum and switch to static when what you're writing becomes impossible to express at compile-time. A surprising number of things can actually be expressed at compile-time.
Mar 13 2014
On 03/13/2014 07:38 AM, ref2401 wrote:Hi. I have this structure: struct MyStruct { enum MyStruct VALUE = MyStruct(5f); static immutable MyStruct value = MyStruct(5f); float data; this(float v) { data = v; } } What's the difference between MyStruct.VALUE and MyStruct.value? How should I decide what to use?enum defines a manifest constant, meaning that it is just a value; there is not one but many MyStruct objects constructed every time VALUE is used in the code. The following run-time asserts prove that two instances have different data members: assert(&MyStruct.VALUE.data != &MyStruct.VALUE.data); On the other hand, there is just one MyStruct.value object: assert(&MyStruct.value == &MyStruct.value); In other words, MyStruct.VALUE is an rvalue but MyStruct.value is an lvalue; you cannot take the address of an rvalue. The following static asserts pass. static assert(!__traits(compiles, &MyStruct.VALUE)); static assert( __traits(compiles, &MyStruct.value)); It shouldn't matter much for such a type but prefer a static immutable for expensive types like arrays. Ali
Mar 13 2014