On 03/15/2017 08:27 PM, WhatMeForget wrote:
>
> One of my D books says: "an enum declared without any braces is called a
> manifest constant." The example shows,
>
> enum string author = "Mike Parker";
>
> Is this equivalent to
> const string author = "Mike Parker";
> or
> immutable string author = "Mike Parker";
>
> I guess what I'm asking is does enum give you some advantages over say
> non-enum constants?

The guideline should be, "prefer enum except when the type is an array except if it's a string." :)

You can think of enum as a text replacement similar to C macros. Whenever you see 'author' in code, it would be as if it was replaced with its value:

    writeln(author);
    writeln("Mike Parker");    // Same as above

The limitation is that just like you cannot take the address of e.g. 42, you can't take the address of an enum:

    // All lines below are compilation errors: "not an lvalue"
    writeln(&42);
    writeln(&"Mike Parker");
    writeln(&author);

const static and immutable have the advantage of being initialized at runtime. This one reads the name from a file:

import std.stdio;

immutable string author;

string makeAuthor() {
    import std.file;
    auto content = read("author_name_file");
    return cast(string)content;
}

shared static this() {
    author = makeAuthor();
}

void main() {
    writeln(author);
}

Ali

Reply via email to