Joseph Rice:

import std.stdio;

void main() {
        enum TEST {
                test1=0,
                test2
        };

        TEST test = TEST.test1;
        
        switch (test) {
                case TEST.test1:
                        writeln("It's test1");
                        break;
                case TEST.test2:
                        writeln("It's test2");
                        break;
                default:
                break;
        }
}

This is how you usually write that code in D:


void main() {
    import std.stdio;

    enum Test { t1, t2 }
    auto test = Test.t1;

    final switch (test) with (Test) {
        case t1:
            writeln("It's t1");
            break;
        case t2:
            writeln("It's t2");
            break;
    }
}


The differences:
- The import is often better in the function.
- Type names (like Test) are better written with just the first letter uppercase. - You often have to carry the type name around, so using shorter names is sometimes OK (like t1 and t2).
- In this code you want a final switch.
- Using with() you avoid repeating the enum type name.

In D you also have anonymous enums:

enum { test1, test2 }

Also, when you refer to C++, it's better to use the "enum class" of C++11.

D enums have some faults, like being weakly typed, having bad error messages, and sometimes being a bit too much long to write (when you pass an enum to a function, the function already knows the name of the enum type. But this is not so bad...).

Bye,
bearophile

Reply via email to